How to Read Data in Python From Csv
This article explains how to load and parse a CSV file in Python.
Starting time of all, what is a CSV ?
CSV (Comma Separated Values) is a uncomplicated file format used to store tabular data, such every bit a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plainly text. Each line of the file is a data record. Each record consists of one or more fields, separated by commas. The use of the comma as a field separator is the source of the name for this file format.
For working CSV files in python, there is an inbuilt module called csv.
Reading a CSV file
Python
import csv
filename = "aapl.csv"
fields = []
rows = []
with open up (filename, 'r' ) as csvfile:
csvreader = csv.reader(csvfile)
fields = side by side (csvreader)
for row in csvreader:
rows.suspend(row)
print ("Total no. of rows: % d" % (csvreader.line_num))
print ( 'Field names are:' + ', ' .join(field for field in fields))
print ( '\nFirst 5 rows are:\n' )
for row in rows[: v ]:
for col in row:
print ( "%10s" % col,end = " " ),
print ( '\n' )
The output of the to a higher place program looks similar this:
The to a higher place example uses a CSV file aapl.csv which can be downloaded from hither.
Run this program with the aapl.csv file in the same directory.
Let united states of america endeavour to sympathize this piece of code.
with open(filename, 'r') every bit csvfile: csvreader = csv.reader(csvfile)
- Here, we start open up the CSV file in READ mode. The file object is named as csvfile. The file object is converted to csv.reader object. We save the csv.reader object as csvreader.
fields = csvreader.next()
- csvreader is an iterable object. Hence, .next() method returns the electric current row and advances the iterator to the adjacent row. Since the first row of our csv file contains the headers (or field names), we save them in a list chosen fields.
for row in csvreader: rows.append(row)
- Now, we iterate through the remaining rows using a for loop. Each row is appended to a list called rows. If you lot try to print each row, one tin can observe that a row is nothing but a list containing all the field values.
print("Total no. of rows: %d"%(csvreader.line_num)) - csvreader.line_num is nothing but a counter which returns the number of rows that have been iterated.
Writing to a CSV file
Python
import csv
fields = [ 'Name' , 'Branch' , 'Twelvemonth' , 'CGPA' ]
rows = [ [ 'Nikhil' , 'COE' , '2' , 'nine.0' ],
[ 'Sanchit' , 'COE' , '2' , '9.ane' ],
[ 'Aditya' , 'IT' , '2' , 'nine.3' ],
[ 'Sagar' , 'SE' , 'one' , 'nine.5' ],
[ 'Prateek' , 'MCE' , '3' , 'vii.8' ],
[ 'Sahil' , 'EP' , '2' , '9.i' ]]
filename = "university_records.csv"
with open (filename, 'w' ) as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
Let us try to understand the above code in pieces.
- fields and rows accept been already defined. fields is a listing containing all the field names. rows is a list of lists. Each row is a list containing the field values of that row.
with open(filename, 'west') equally csvfile: csvwriter = csv.writer(csvfile)
- Here, nosotros first open the CSV file in WRITE mode. The file object is named as csvfile. The file object is converted to csv.writer object. We save the csv.author object as csvwriter.
csvwriter.writerow(fields)
- Now nosotros utilise writerow method to write the first row which is nothing just the field names.
csvwriter.writerows(rows)
- We utilize writerows method to write multiple rows at once.
Writing a dictionary to a CSV file
Python
import csv
mydict = [{ 'branch' : 'COE' , 'cgpa' : '9.0' , 'name' : 'Nikhil' , 'yr' : '2' },
{ 'branch' : 'COE' , 'cgpa' : '9.i' , 'name' : 'Sanchit' , 'year' : '2' },
{ 'branch' : 'It' , 'cgpa' : 'ix.iii' , 'name' : 'Aditya' , 'year' : '2' },
{ 'co-operative' : 'SE' , 'cgpa' : '9.5' , 'name' : 'Sagar' , 'year' : 'one' },
{ 'branch' : 'MCE' , 'cgpa' : 'seven.8' , 'proper noun' : 'Prateek' , 'year' : '3' },
{ 'co-operative' : 'EP' , 'cgpa' : '9.1' , 'name' : 'Sahil' , 'year' : 'two' }]
fields = [ 'name' , 'branch' , 'year' , 'cgpa' ]
filename = "university_records.csv"
with open (filename, 'west' ) as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
writer.writeheader()
author.writerows(mydict)
In this example, we write a lexicon mydict to a CSV file.
with open(filename, 'due west') every bit csvfile: writer = csv.DictWriter(csvfile, fieldnames = fields)
- Here, the file object (csvfile) is converted to a DictWriter object.
Here, nosotros specify the fieldnames as an argument.
writer.writeheader()
- writeheader method but writes the first row of your csv file using the pre-specified fieldnames.
writer.writerows(mydict)
- writerows method merely writes all the rows simply in each row, information technology writes but the values(not keys).
So, in the finish, our CSV file looks like this:
Important Points:
- In csv modules, an optional dialect parameter can be given which is used to define a fix of parameters specific to a detail CSV format. By default, csv module uses excel dialect which makes them compatible with excel spreadsheets. You can define your ain dialect using register_dialect method.
Hither is an example:
At present, while defining a csv.reader or csv.writer object, nosotros tin specify the dialect like
this:
- Now, consider that a CSV file looks like this in plain-text:
- We notice that the delimiter is not a comma but a semi-colon. Also, the rows are separated by ii newlines instead of one. In such cases, we can specify the delimiter and line terminator as follows:
So, this was a cursory, still curtailed discussion on how to load and parse CSV files in a python program.
This blog is contributed by Nikhil Kumar. If yous similar GeeksforGeeks and would like to contribute, you tin also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article actualization on the GeeksforGeeks main folio and help other Geeks.
Please write comments if yous find annihilation incorrect, or you desire to share more information about the topic discussed to a higher place.
Source: https://www.geeksforgeeks.org/working-csv-files-python/
0 Response to "How to Read Data in Python From Csv"
Enviar um comentário