Python CSV File Handling
- CSV (Comma-separated values) is a common data exchange format used by the applications to produce and consume data.
- A CSV file is a simple text file where each line contains a list of values (or fields) delimited by commas (mostly), but you will encounter CSV files where data is delimited using tab (\t) or pipe (|) or any other character.
- The first line of the CSV file represents the header containing a list of column names in the file.
- CSV file is commonly used to represent tabular data
- See the following table
Name | Class | Section |
Amit | X | A |
Sumit | XI | B |
Ashish | XII | C |
The above table will be stored in CSV format as follows:
If the values in the table contain comma(,) like below in column Address
Then in CSV it will be stored like below (Values containing comma will be enclosed in double quotes)
Python Provides CSV module to work with csv file:
Main Functions are:
- reader()
- writer()
- DictReader()
- DictWriter()
- reader() function : This function help us to read the csv file. This function takes a file object and returns a _csv.reader object that can be used to iterate over the contents of a CSV file.
How to read entire data from data.csv file?
Let we try to read the following file ie “data.csv”
data.csv
CODINGÂ Â | OUTPUTÂ Â |
import csv f = open(“data.csv”, ‘r’) row = csv.reader(f) for i in row : print(i) | [‘Name’ , ‘Class’ , ‘Subject’] [‘Amit’ , ‘XII’ , ‘ CS’] [‘Sumit’ , ‘X’ , ‘IP’] Notice that each line in the CSV file is returned as a list of strings |
Line-wise explanation of the code
- The first line is importing a csv module.
- This line is opening a file (data.csv) in reading mode and f is file object or file handle.
- This line is returning a csv.reader object that can be used to iterate over csv file contents
- We are using loop on the object which is returned by the previous line
CODINGÂ Â | OUTPUTÂ Â |
import csv f = open(“data.csv”, ‘r’) row = csv.reader(f) print(row) | Returns the memory address where csv.reader object is stored |
How to read specific column from data.csv?
CODING | OUTPUT | Actual Data of File |
import csv f = open(“data.csv”, ‘r’) row = csv.reader(f) for i in row : print(i[0] , i[2]) The above code is reading first and third column from “data.csv” file | Name Subject Amit CS Sumit IP | [‘Name’ , ‘Class’ , ‘Subject’] [‘Amit’ , ‘XII’ , ‘ CS’] [‘Sumit’ , ‘X’ , ‘IP’] |
If you want to skip the First Row (header of the table)
CODING  | OUTPUT  | Actual Data of File  |
import csv f = open(“data.csv”, ‘r’) row = csv.reader(f) next(row) for i in row : print(i[0] , i[2]) next () function will jump to the next row. import csv f = open(“data.csv”, ‘r’) row = csv.reader(f) next(row) next(row) for i in row : print(i[0] , i[2]) If we use the next() function two times then it will skip two lines from beginning | [ ‘Amit’ , ‘CS’] [‘Sumit’ , ‘IP’ ] [‘Sumit’ , ‘IP’ ] | [‘Name’ , ‘Class’ , ‘Subject’] [‘Amit’ , ‘XII’ , ‘ CS’] [‘Sumit’ , ‘X’ , ‘IP’] [‘Name’ , ‘Class’ , ‘Subject’] [‘Amit’ , ‘XII’ , ‘CS’] [‘Sumit’ , ‘X’ , ‘IP’] |
_______________________________________________________
If there is any other delimiter other than comma like in the following file
CODINGÂ Â | OUTPUTÂ Â |
import csv f = open(“data.csv”, ‘r’) row = csv.reader(f, delimiter = ‘l’) for i in row : print(i) | [‘id’ , ‘name’ , ’email’ , ‘salary’] [‘1’ , ‘Amit’ , ‘amit@mail.com’ , ‘25000’] [‘2’ , ‘Sumit’ , ‘sumit@mail.com’ , ‘30000’] [‘3’ , ‘Ashu’ , ‘ashu@mail.com’ , ‘40000’] |
- writer() function : This function help us to write data in a csv file. It accepts the same argument as the reader() function but returns a writer object (i.e _csv.writer)
There are two main methods used in writing in csv file
- writerow()
- writerows()
Example using writerow()
CODINGÂ Â | DATA.CSVÂ Â |
import csv f = open(“data.csv”, ‘w’) wr = csv.writer(f) wr.writerow([‘Name’ , ‘Class’]) wr.writerow([‘Amit’ , ‘XII’]) f.close( ) | Name , Class ‘Amit’ , ‘XII’ |
Example using writerows()
CODINGÂ Â | DATA.CSVÂ Â |
import csv fields = [‘Name’ , ‘Class’ , ‘Subject’] rows = [[“Amit” , ‘XII’ , ‘CS’] , [‘Sumit’ , ‘X’ , ‘IP’] , [‘Ashu’ , ‘XI’ , ‘CS’]] f = open(“data.csv” , ‘w’ , newline = ‘ ‘) wr = csv.writer(f) wr.writerow(fields) wr.writerows(rows) f.close | Name, Class, Subject Amit, XII, CS Sumit, X, IP Ashu, XI, CS Â |
Reading a CSV file with DictReader:
This function(DictReader) is working similar to reader(). This function return lines as a dictionary instead of list.
CODING  | OUTPUT  | data.csv |
import csv f = open(“data.csv” , ‘r’) row = csv.DictReader(f) for i in row: print(i) Â | {‘Name’ : ‘Amit, ‘Class’ : ‘XII’} {‘Name’ : ‘Sumit, ‘Class’ : ‘X’} {‘Name’ : ‘Ashu, ‘Class’ : ‘XI’} Â | Name, Class Amit, XII Sumit, X Ashu, XI Â |
This CSV file has no header. So we have to provide field names via the fieldnames parameter
CODINGÂ Â |
import csv f = open(“data.csv” , ‘r’) row = csv.DictReader(f, fieldnames = [‘Name’ , ‘Class’ , ‘Subject’]) for i in row: print(i) |
OUTPUTÂ Â |
{‘Name’ : ‘Amit, ‘Class’ : ‘XII’ , ‘Subject’ : ‘CS’} {‘Name’ : ‘Sumit, ‘Class’ : ‘X’ , ‘Subject’ : ‘IP’} {‘Name’ : ‘Ashu, ‘Class’ : ‘XI’ , ‘Subject’ : ‘CS’} |
data.csv  |
Amit, XII, CS Sumit, X, IP Ashu, XI, CS |
Related Post :
10 Important Questions of CSV File Handling in Python
10 Important Questions of Text File Handling in Python
10 Important Questions of Binary File Handling in Python
Handout of Text File Handling in Python
40+ Important Python File Handling Practice Questions
Handout of Binary File Handling in Python
Class 12 Computer Science Sample Paper 2020-2021.
Class 12 Computer Science Sample Paper Marking Scheme
Class 12 Computer Science Test Series