CSV (Comma Separated Values) format is the most common import and export format for spreadsheets and databases. It is one of the most common methods for exchanging data between applications and popular data format used in Data Science. It is supported by a wide range of applications. A CSV file stores tabular data in which each data field is separated by a
delimiter(comma in most cases). To represent a CSV file, it must be saved with the
.csv file extension.
Reading from CSV file
Python contains a module called
csv for the handling of CSV files. The reader class from the module is used for reading data from a CSV file. At first, the CSV file is opened using the open() method in ‘r’ mode(specifies read mode while opening a file) which returns the file object then it is read by using the
reader() method of CSV module that returns the reader object that iterates throughout the lines in the specified CSV document.
Syntax:
csv.reader(csvfile, dialect='excel', **fmtparams
Note: The ‘with‘ keyword is used along with the
open() method as it simplifies exception handling and automatically closes the CSV file.
Example:
Consider the below CSV file –
import csv
with open('Giants.csv', mode ='r')as file:
csvFile = csv.reader(file)
for lines in csvFile:
print(lines)
|
Output:
[['Steve', 13, 'A'],
['John', 14, 'F'],
['Nancy', 14, 'C'],
['Ravi', 13, 'B']]
Writing to CSV file
csv.writer class is used to insert data to the CSV file. This class returns a writer object which is responsible for converting the user’s data into a delimited string. A CSV file object should be opened with newline=” otherwise, newline characters inside the quoted fields will not be interpreted correctly.
Syntax:
csv.writer(csvfile, dialect='excel', **fmtparams)
csv.writer class provides two methods for writing to CSV. They are
writerow() and
writerows().
- writerow(): This method writes a single row at a time. Field row can be written using this method.
Syntax:
writerow(fields)
- writerows(): This method is used to write multiple rows at a time. This can be used to write rows list.
Syntax:
writerows(rows)
Example:
import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
filename = "university_records.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
|
Output:

We can also write dictionary to the CSV file. For this the CSV module provides the csv.DictWriter class. This class returns a writer object which maps dictionaries onto output rows.
Syntax:
csv.DictWriter(csvfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’, *args, **kwds)
csv.DictWriter provides two methods for writing to CSV. They are:
- writeheader():
writeheader() method simply writes the first row of your csv file using the pre-specified fieldnames.
Syntax:
writeheader()
- writerows():
writerows method simply writes all the rows but in each row, it writes only the values(not keys).
Syntax:
writerows(mydict)
Example:
import csv
mydict =[{'branch': 'COE', 'cgpa': '9.0', 'name': 'Nikhil', 'year': '2'},
{'branch': 'COE', 'cgpa': '9.1', 'name': 'Sanchit', 'year': '2'},
{'branch': 'IT', 'cgpa': '9.3', 'name': 'Aditya', 'year': '2'},
{'branch': 'SE', 'cgpa': '9.5', 'name': 'Sagar', 'year': '1'},
{'branch': 'MCE', 'cgpa': '7.8', 'name': 'Prateek', 'year': '3'},
{'branch': 'EP', 'cgpa': '9.1', 'name': 'Sahil', 'year': '2'}]
fields = ['name', 'branch', 'year', 'cgpa']
filename = "university_records.csv"
with open(filename, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames = fields)
writer.writeheader()
writer.writerows(mydict)
|
Output:
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.
Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Last Updated :
22 Jun, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...