0% found this document useful (0 votes)
3 views4 pages

Reading and Writing CSV Files in Python - GeeksforGeeks

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 4

1/20/2021 Reading and Writing CSV Files in Python - GeeksforGeeks

Related Articles Save for later

Reading and Writing CSV Files in Python


Last Updated : 22 Jun, 2020

CSV (Comma Separated Values) format is the most common impor t and expor t 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 suppor ted

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 .c sv file extension.

Reading from CSV file

P ython 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 :

We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Got It !
acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/reading-and-writing-csv-files-in-python/ 1/8
1/20/2021 Reading and Writing CSV Files in Python - GeeksforGeeks

Consider the below CSV file –

import csv

# opening the CSV file


with open('Giants.csv', mode ='r')as file:

# reading the CSV file


csvFile = csv.reader(file)

# displaying the contents of the CSV 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 inser t data to the CSV file. This class returns a writer object

which is responsible for conver ting the user ’s data into a delimited string. A CSV file
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Got It !
acknowledge that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/reading-and-writing-csv-files-in-python/ 2/8
1/20/2021 Reading and Writing CSV Files in Python - GeeksforGeeks

object should be opened with newline=” other wise, newline characters inside the quoted

fields will not be interpreted correctly.

Syntax :

csv.writer(csvfile, dialect='excel', **fmtparams)

c sv.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 :

# Python program to demonstrate


# writing to CSV

import csv

# field names
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Got It !
fieldsacknowledge
= ['Name', 'Branch',
that you 'Year',
have read and 'CGPA']
understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/reading-and-writing-csv-files-in-python/ 3/8
1/20/2021 Reading and Writing CSV Files in Python - GeeksforGeeks

# data rows of csv file


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']]

# name of csv file


filename = "university_records.csv"

# writing to csv file


with open(filename, 'w') as csvfile:
# creating a csv writer object
csvwriter = csv.writer(csvfile)

# writing the fields


csvwriter.writerow(fields)

# writing the data rows


csvwriter.writerows(rows)

Output :

We can also write dictionar y to the CSV file. For this the CSV module provides the

c sv.DictWriter class. This class returns a writer object which maps dictionaries onto

output rows.

Syntax :

c sv.DictWriter(c svfile, fieldnames, restval=”, extrasaction=’raise’, dialect=’excel’,

*args, **kwds)

c sv.DictWriter provides two methods for writing to CSV. They are:

writeheader(): writeheader() method simply writes the first row of your c sv file using
the pre-specified fieldnames.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
Got It !
acknowledge
Syntax : that you have read and understood our Cookie Policy & Privacy Policy

https://www.geeksforgeeks.org/reading-and-writing-csv-files-in-python/ 4/8

You might also like