Chapter 5 – Part 3
File Handling – CSV Files
Class – XII
Subject: Computer Science
What is a CSV FILE
CSV stands for “Comma-Separated Values”.
CSV is a simple file format used to store tabular
data, such as a spreadsheet or database.
Files in the CSV format can be used in spreadsheet
programs, such as Microsoft Excel or OpenOffice
Calc.
A comma-separated values file is a delimited text file
that uses a comma to separate values.
Each line of the file is a data record. Each record
consists of one or more fields, separated by
commas.
Example of a CSV File
Working with CSV Files in Python
To work with CSV Files in Python, we must import
csv module as shown below -
import csv
After that, open() function is used to open the
file(Same as in case of text files)
Reading from CSV file
Following are steps to read data from CSV files in Python
1. import csv module.
2. Use open() function to open csv file, it will return the file object.
3. Pass this file object to csv.reader() function. It will return the reader
object
Syntax to use csv.reader() function—
<object> = csv.reader(<File Object> , delimiter = <delimiter of file>)
For example –
MYDATA = csv.reader(MyFile , delimiter = ‗,‘)
This statement will read the data from CSV and create a reader object.
Now you can read data from reader object using for loop.
Example Program 1
Write a program in python to read data from a
csv file and print data on screen
import csv
MYFILE = open(r"C:\Users\Brahm\Desktop\data\Students.csv","r")
MyData = csv.reader(MYFILE , delimiter = ',')
for row in MyData:
print(row)
MYFILE.close()
Example program 2
Write a program to read a csv file Students.csv and calculate total
number of students scoring more than 33 marks. Format of CSV
file is as below-
RollNo, Name,Class,Marks
import csv
MYFILE = open(r"C:\Users\Brahm\Desktop\data\Students.csv","r")
MyData = csv.reader(MYFILE , delimiter = ',')
count = 0
for row in MyData:
if row[0] =="RollNo":
pass
else:
if int(row[3]) > 33:
count = count + 1
print("No. of students scoring marks more than 33 - ", count)
MYFILE.close()
Advantages of Using CSV Files in
programming
• CSV is faster to handle.
• CSV is smaller in size.
• CSV is easy to generate and import onto a
spreadsheet or database.
• CSV is human readable and easy to edit
manually.
• CSV is simple to implement and parse.
• CSV is processed by almost all existing
applications.
Opening a file using ‗with‘ keyword
Generally we open file as shown below—
MYFILE = open(“student.csv, “r”)
There is an another way to open file- Using ‗with‘—
with open(“student.csv, “r”) as MYFILE:
<Statements to process MYFILE>
When a file is opened using ‗with‘ keyword, there is no
need to explicitly close it. File is automatically closed
when block ends
Example Program 3
Write a program in python to read data from a csv
file using „with‟ keyword and print data on screen
import csv
with open(r"C:\Users\Brahm\Desktop\data\Students.csv","r") as MYFILE:
MyData = csv.reader(MYFILE , delimiter = ',')
for row in MyData:
print(row)
Example Program 4
Write a program to count the number of records
present in ―student.csv‖ file.
import csv
MYFILE = open(r"C:\Users\Brahm\Desktop\data\Students.csv","r")
MY_READER = csv.reader(MYFILE)
COUNT = 0
for row in MY_READER:
COUNT = COUNT + 1
MYFILE.close()
print("No. of records in file are : ", COUNT)
Writing to a CSV File
Open the file in write only(w) or append (a)
mode.
To write to a CSV file in Python, we can use
the csv.writer() function.
The csv.writer() function returns a writer
object.
This writer object can later be used to write
into CSV files using the writerow() function or
writerows() function
Using writerow() and writerows()
function
writerow(<list>) – It writes only 1 row at a time. Fields to be
written should be a list of elements/fields
Example – [12, ―Ajay‖ , 95]
while using writerow(), you do not need to add a new line
character (or other EOL indicator) to indicate the end of the
line; writerow() does it for you as necessary
writerows(<list>) – It writes multiple rows at a time. All rows
to be written should be enclosed in a list. Each row itself is
a list of fields.
Example – [ [12, ―Ajay‖ , 95] , [13, ―Rahul‖ , 96]
Program to write data onto
―student‖ CSV file using
writerow() method.
import csv
MY_FILE = open("students.csv","w“)
MY_WRITER = csv.writer(MY_FILE,delimiter =',')
MY_WRITER.writerow(['RollNo','Name','Marks'])
MY_WRITER.writerow([1,'Rauhl',90])
MY_WRITER.writerow([2,'Ajay',91])
MY_FILE.close()
Program to write data onto ―student‖
CSV file using writerows() method.
import csv
MY_FILE = open("students.csv","w")
MY_WRITER = csv.writer(MY_FILE,delimiter =',')
DATA = [['RollNo','Name','Marks'],[1,'Rauhl',90],[2,'Ajay',91]]
MY_WRITER.writerows(DATA)
MY_FILE.close()