Page Contents
In this tutorial we will learn about csv file handling in Python .The csv (comma separated values) file is the easiest and simplest way to store any tabular data. The .csv extension is used to save the csv file.
Python has a built-in module csv to work with csv files. So, We need to import the csv module before working on the csv file.
import csv
How to read csv file in Python
There are two methods in csv module to read csv file in Python, one is reader()
method and the other is DictReader()
method. To read csv file, first we need to open the csv file in “r” (read) mode.
A sample of csv file is given below . We will save it as csv_sample1.csv in the current folder where we are working now . The first row of the given file is the header.
country,capital,type
Abkhazia,Sukhumi,countryCapital
Afghanistan,Kabul,countryCapital
Akrotiri and Dhekelia,Episkopi Cantonment,countryCapital
Albania,Tirana,countryCapital
Python CSV reader() method
The reader()
method returns a reader object whose each item is a list, which can be read by iterating each row with the help of for-loop.
Minimal Syntax of reader() method
csv.reader(csvfile)
Parameters of reader() method
csvfile = It is the csv file that we want to read.
Examples of Python CSV reader() method
Example 1: Read csv file in Python using csv.reader() method
import csv
with open("csv_sample1.csv","r",newline="") as csv_file:
# creating reader object
csv_reader=csv.reader(csv_file)
# reading the file
for row in csv_reader:
print(row)
['country', 'capital', 'type'] ['Abkhazia', 'Sukhumi', 'countryCapital'] ['Afghanistan', 'Kabul', 'countryCapital'] ['Akrotiri and Dhekelia', 'Episkopi Cantonment', 'countryCapital'] ['Albania', 'Tirana', 'countryCapital']
- In the above code the csv module was first imported .
- Then the file “csv_sample1.csv” is opened in “r” mode.
- Then the
reader()
method returns the reader-object that is stored in thecsv_reader
variable. - Then each row is printed by iterating
csv_reader
with for-loop.
Note :
When we open a csv file, it is a good habit to use newline = ""
in the argument .
Python CSV DictReader() method
The DictReader()
method returns a DictReader object whose every item is a dictionary, which can be read by iterating each row with the help of for-loop.
Minimal Syntax of DictReader() method
csv.DictReader(csvfile)
Parameters of DictReader() method
csvfile = It is the csv file that we want to read.
Examples of Python CSV DictReader() method
Example 1: Read csv file in Python using csv.DictReader() method
import csv
with open("csv_sample1.csv","r",newline="") as csv_file:
# creating reader object
csv_dictReader= csv.DictReader(csv_file)
# reading the file
for row in csv_dictReader:
print(row)
{'country': 'Abkhazia', 'capital': 'Sukhumi', 'type': 'countryCapital'} {'country': 'Afghanistan', 'capital': 'Kabul', 'type': 'countryCapital'} {'country': 'Akrotiri and Dhekelia', 'capital': 'Episkopi Cantonment', 'type': 'countryCapital'} {'country': 'Albania', 'capital': 'Tirana', 'type': 'countryCapital'}
- In the above code the csv module was first imported .
- Then the file “csv_sample1.csv” is opened in “r” mode.
- Then the
DictReader()
method returns the reader object that is stored in thecsv_dictReader
variable. - Then each row is printed by iterating
csv_dictReader
with for-loop.
Although we have five rows with headers in our file but DictReader()
method has printed only four lines here. Each line of which is a dictionary. Notice that the key of each dictionary is each element of the header and the value is the corresponding element of that key for each line. Since there is a header and four lines, four dictionaries have been printed.
So, while applying DictReader()
method we need to check if there is any header in the file, if there is header then DictReader()
method could be applied.
How to write to a csv file in Python
There are two methods in csv module to write to a csv file in Python, one is writer()
method and the other is DictWriter()
method. To write to a csv file, first we need to open the csv file in “w” (write) or “a” (append) mode.
Python CSV writer() method
The writer()
method returns a writer-object that converts a given string into a delimited string. Then we will apply the writerow()
and writerows()
method to the writer-object to write the delimited string to a csv file.
Minimal Syntax of writer() method
csv.writer(f)
Parameters of writer() method
f = It is the csv file in which we want to write.
Examples of Python CSV writer() method
Example 1: Write to a csv file in Python using writer() method line by line
import csv
with open("csv_sample.csv","w",newline="") as csv_file:
# creating writer object
csv_writer=csv.writer(csv_file)
# writting header into the file
csv_writer.writerow(['country', 'capital', 'type'])
# writting rows into the file
csv_writer.writerow(['Abkhazia', 'Sukhumi', 'countryCapital'])
csv_writer.writerow(['Afghanistan', 'Kabul', 'countryCapital'])
- In the above code the csv module was first imported
- Then the “csv sample.csv” file is opened in “w” mode.
- Then the
writer()
method returns the writer object that has been stored in thecsv_writer
variable. - Then write to the file using the
writerow()
method.
In the line csv_writer.writerow (['country', 'capital', 'type'])
csv_writer
first converts ['country', 'capital', 'type']
to a delimited string . Then write this delimited string to the file using the writerow()
method.
Example 2: Write to a csv file in Python using writer() method
import csv
# row list to write all the row
row_list=[['country', 'capital', 'type'],
['Abkhazia', 'Sukhumi', 'countryCapital'],
['Afghanistan', 'Kabul', 'countryCapital'],
['Akrotiri and Dhekelia', 'Episkopi Cantonment', 'countryCapital'],
['Albania', 'Tirana', 'countryCapital']]
with open("csv_sample.csv","w",newline="") as csv_file:
csv_writer=csv.writer(csv_file)
csv_writer.writerows(row_list)
In the above code, multiple lines have been written using writerows()
method instead of writerow()
method.
Python CSV DictWriter() method
The DictWriter()
method is used to write to a csv file from a python dictionary.
Minimal Syntax of DictWriter() method
csv.DictWriter(f,fieldnames)
Parameters of DictWriter() method
- f = It is the csv file in which we want to write.
- fieldnames = It is a list so that the headers of the file are given in a specific order.
Examples of Python CSV DictWriter() method
Example 1: Write to a csv file in Python using DictWriter() method
import csv
with open("csv_sample.csv","w",newline="") as csv_file:
# list of file header or dictionary key
header=['country', 'capital', 'type']
# creating writer object
csv_dictWriter=csv.DictWriter(csv_file,fieldnames=header)
# writting file header into the file
csv_dictWriter.writeheader()
# writting other rows into the file
csv_dictWriter.writerow({'country': 'Abkhazia', 'capital': 'Sukhumi', 'type': 'countryCapital'})
csv_dictWriter.writerow({'country': 'Afghanistan', 'capital': 'Kabul', 'type': 'countryCapital'})
- In the above code the csv module was first imported
- Then the “csv sample.csv” file is opened in “w” mode.
- The
DictWriter()
method then returns the dictwriter object that is stored in thecsv_dictWriter
variable. - Then write to the file using the
writerow()
method.
Note :
The writerows()
method also can be used in dictwriter-object like writer-object.
Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .