CSV Files in Python
Contents
- 1 What is a CSV File?
- 2 What are CSV methods provided by Python?
- 3 How to read a CSV File in Python?
- 4 How to write in a CSV File in Python?
- 5 How to modify existing rows in a CSV file using Python?
- 6 How to append new rows to CSV file in Python?
- 7 How to write CSV file into a Dictionary in Python?
- 8 How to use Custom dialect in Python?
What is a CSV File?
CSV stands for Comma Separated Values, is one of the popular ways of storing tabular data in the file. Python provides an easy way to work with CSV file. It has a csv module to read and write data in the CSV file.
Let us consider an example of a CSV file with three attributes, SN, Name, and City. We can visualize the data in table format as below:_
SN | Name | City |
1 | John Doe | New York |
2 | Freddie Moore | Texas |
3 | Troy Jackson | California |
So, to store this data, we make a csv file named people.csv and store the content as comma separated.
1, John Doe, New York
2, Freddie Moore, Texas
3, Troy Jackson, California
What are CSV methods provided by Python?
Python provides a set of methods to work on with CSV files. It provides a csv module that can be imported into your application and use the following methods to start working with CSV files.
Method | Description |
csv.reader | returns a reader object which iterates over lines of a CSV file |
csv.writer | returns a writer object which writes data into CSV file |
csv.register_dialect | registers a CSV dialect |
csv.unregister_dialect | unregisters a CSV dialect |
csv.get_dialect | returns a dialect with the given name |
csv.list_dialects | returns all registered dialects |
csv.field_size_limit | returns the current maximum field size allowed by the parser |
How to read a CSV File in Python?
To read a csv file in Python, we use csv.reader() module. Let us use the people.csv created as above containing three names and address of people.
import csv with open("people.csv", "r") as csvFile: reader = csv.reader(csvFile) for row in reader: print(row)
We get the following output:-
[‘1’, ‘ John Doe’, ‘ New York’]
[‘2’, ‘ Freddie Moore’, ‘ Texas’]
[‘3’, ‘ Troy Jackson’, ‘ California’]
How to write in a CSV File in Python?
In python, we use csv.writer module to write in a csv file.
import csv csvData = [['Name of Person', 'Age'], ['Peter', '22'], ['Jasmine', '21'], ['Sam', '24']] with open('person.csv', 'w') as csvFile: writer = csv.writer(csvFile) writer.writerows(csvData)
The resulting output is the file named person.csv with the following content
Peter,22
Jasmine,21
Sam,24
How to modify existing rows in a CSV file using Python?
To update any row, we will need to update the whole CSV file. The use of the writerows() method for csv.writer() provides updating of the list with ease. Remember, the indexing of the list starts with 0. In the following example, we are going to update the 2nd-row person name from Freddie Moore to Marie keeping the address same.
import csv row = ['2', ' Marie', ' Texas'] with open('people.csv', 'r') as readFile: reader = csv.reader(readFile) lines = list(reader) lines[2] = row with open('people.csv', 'w') as writeFile: writer = csv.writer(writeFile) writer.writerows(lines)
This outputs the modified file people.csv with the following content:-
1, John Doe, New York
2, Marie, Texas
3, Troy Jackson, California
How to append new rows to CSV file in Python?
We can open a file in append mode and write csv row to it. Let’s append a new user “Danny” with address “New York” with the help of following code:-
import csv row = ['4', ' Danny', ' New York'] with open('people.csv', 'a') as csvFile: writer = csv.writer(csvFile) writer.writerow(row)
This results in an updated version of the people.csv file:-
1, John Doe, New York
2, Marie, Texas
3, Troy Jackson, California
4, Danny, New York
How to write CSV file into a Dictionary in Python?
Using DictWriter() class of CSV module, we can write a CSV file into a dictionary. It works similar to the writer() function but creates an object which maps data into a dictionary. The keys are given by the field names parameter.
import csv data = [ {'mountain' : 'Everest', 'height': '8848'}, {'mountain' : 'K2', 'height': '8611'}, {'mountain' : 'Kanchenjunga', 'height': '8586'} ] with open('peak.csv', 'w') as csvFile: fields = ['mountain', 'height'] writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() writer.writerows(data)
The output results in peak.csv file with the following content:-
Everest,8848
K2, 8611
Kanchenjunga,8586
How to use Custom dialect in Python?
A dialect is a class of CSV module which helps to define parameters for reading and writing CSV. It allows you to create, store, and re-use various formatting parameters for your data.
import csv csv.register_dialect('myDialect1', delimiter = ',', skipinitialspace=True) csv.register_dialect('myDialect2', delimiter = ',' quoting=csv.QUOTE_ALL, skipinitialspace=True) reader = csv.reader(f, dialect='myDialect1')