Python Read Csv One Line at a Time
Read CSV Line by Line in Python
- File Structure of a CSV File
- Read CSV File Line by Line Using
csv.readerin Python - Read CSV File Line by Line Using
DictReaderObject in Python - Conclusion
In Python, reading a file and printing information technology column-wise is mutual. But reading the file row by row might get a scrap confusing sometimes.
This article will tackle how to read a CSV file line by line in Python. We will employ the python csv module to deal with the CSV files in Python.
Earlier reading the CSV file line by line, let u.s. get-go look at the file format of the CSV files. This will help us to manipulate the CSV files in a amend way.
File Structure of a CSV File
CSV stands for Comma Separated Values; it is a simple file format that stores information in tables. These tables could exist in the grade of a spreadsheet or a database.
We tin likewise make a CSV file in a unproblematic text editor like Notepad. Each CSV file line corresponds to one record of the table.
Moreover, each tape has one or more fields. The cross-department of a field and a record is called a jail cell. These fields are separated by commas (,).
Sometimes, we also call this comma a delimiter. Note that this format gets its proper name from using the comma equally a field separator. CSV files are widely used because of their compatibility with many programs, databases, spreadsheets, and word processing software.
Let u.s.a. now create a CSV file using the file construction described above. After creating the file, nosotros volition read the CSV file line by line using different functions.
We can create a CSV file using a spreadsheet in Microsoft Excel. Notwithstanding, if you don't have Microsoft Excel installed in your system, you tin utilize Notepad or other text editors to make a CSV file.
Nosotros tin can modify the file extension to .csv to do this. As well, do not forget to follow the format of a CSV file. Here are all the steps nosotros need to perform.
- Open a text editor and write the content in the correct CSV format. The headers, every bit well equally the records, are comma-separated. Each record starts in a new line. This is shown beneath:
Curlicue Number,Name,Subject 1,Harry Potter,Magical Creatures 2,Ron Weasley,Divination iii,Hermione Granger,Night arts Save this file as Demo.csv. The CSV file volition be created successfully.
Nosotros can use the open() function to open the CSV file in Python. However, we prefer to use the python csv module made solely for this purpose. To use the csv module, we must import it first.
import csv We will use the Demo.csv file that we have already created to demonstrate. The file looks every bit follows:
Roll Number,Name,Subject i,Harry Potter,Magical Creatures ii,Ron Weasely,Divination 3,Hermione Granger,Dark arts To read the content of this CSV line by line in Python, we will use the csv module, which further provides 2 classes. These classes are csv.reader and csv.DictReader.
Permit u.s.a. await at these classes i by one.
Read CSV File Line by Line Using csv.reader in Python
The csv.reader class of the csv module enables us to read and iterate over the lines in a CSV file as a list of values. Look at the example below:
from csv import reader # open file with open("Demo.csv", "r") equally my_file: # laissez passer the file object to reader() file_reader = reader(my_file) # do this for all the rows for i in file_reader: # impress the rows print(i) We use the reader object to iterate over the rows of the Demo.csv file. The reader object acts as an iterator. This makes sure that only one line stays in the retention at 1 time.
Output:
['Roll Number', 'Name', 'Subject'] ['1', 'Harry Potter', 'Magical Creatures'] ['2', 'Ron Weasley', 'Divination'] ['iii', 'Hermione Granger', 'Dark arts'] Let us await at the functions used here.
Python's open() function is used to open a file. Once information technology opens a file, it returns a file object.
Syntax:
open(file_name, mode) The parameter fashion specifies the mode nosotros desire to open the file. It can exist read, append, write, or create.
The reader() role is used to read a file. Information technology returns an iterable reader object. In the above instance, this iterable object is file_reader, which must be clear from the use of for loop.
In the above instance, the headers are also printed. We can impress a CSV file without a header as well. Await at the following case:
from csv import reader # skip the showtime line(the header) with open('Demo.csv', 'r') as my_file: file_csv = reader(my_file) caput = next(file_csv) # bank check if the file is empty or non if head is non None: # Iterate over each row for i in file_csv: # print the rows print(i) Output:
['ane', 'Harry Potter', 'Magical Creatures'] ['ii', 'Ron Weasley', 'Divination'] ['3', 'Hermione Granger', 'Dark arts'] Here, the headers are not printed. This approach works similarly to the previous arroyo except that we skip the kickoff row during iteration. We have used the adjacent() part to skip the header.
The next() function in Python returns the adjacent item present in an iterator. Its syntax is described beneath.
Syntax:
side by side(iterable_object/iterable, default) Iterable or iterable object is the set of values through which we accept to iterate. default is an optional parameter that is returned by the iterable if it reaches its terminate.
Read CSV File Line by Line Using DictReader Object in Python
csv.reader reads and prints the CSV file every bit a list.
However, the DictReader object iterates over the rows of the CSV file as a lexicon. The mode csv.reader returns each row as a list, ObjectReader returns each row as a dictionary.
Await at the instance beneath:
from csv import DictReader #open up the file with open up('Demo.csv', 'r') as my_file: #passing file object to DictReader() csv_dict_reader = DictReader(my_file) #iterating over each row for i in csv_dict_reader: #print the values print(i) Output:
{'Whorl Number': '1', 'Proper noun': 'Harry Potter', 'Subject field': 'Magical Creatures'} {'Roll Number': '2', 'Name': 'Ron Weasley', 'Subject': 'Divinition'} {'Curl Number': '3', 'Name': 'Hermione Granger', 'Discipline': 'Dark arts'} The DictReader function is similar to the reader office except for how it returns the information. It maps and returns the values as a dictionary where the field names act equally keys of the dictionary and the values consist of the data in a particular row.
Determination
In this article, nosotros discussed the basics of CSV. Nosotros too saw the two ways to read a CSV line by line in Python. We also saw how we could create a CSV file on our own using a text editor similar Notepad.
Write for the states
DelftStack manufactures are written by software geeks like y'all. If you also would like to contribute to DelftStack by writing paid manufactures, you can check the write for usa folio.
Related Article - Python CSV
Related Article - Python File
Source: https://www.delftstack.com/howto/python/read-csv-line-by-line-in-python/
Post a Comment for "Python Read Csv One Line at a Time"