File Handling
CSV Files
Introduction of CSV Files
● CSV File: Comma Separated Values
● CSV files are delimited files that store tabular data (data stored in rows and
columns like databases or spreadsheets) where comma delimits/separate every
value.
● Default Delimiter(Separator Character) of CSV files is the comma(,)
● Other delimiters include tab(\t), colon (:), pipe(I), and semi-colon(;) characters.
● CSV files are also text files. All text files functions will be applicable on it but it is
better to handle these files with CSV module.
● Extension of CSV files: .csv
Opening/Closing CSV Files
1. Specify the file extension as .csv
2. Open the file like other text files:-
f= open(“[Link]”, “w”)
fh= open(“[Link]”, “r”)
Where f and fh are file handles/file objects
3. Closing of CSV Files like:
[Link]()
** File Modes: “r”, “w”, “a”, “r+”, “w+”, “a+”
Role of Argument Newline in opening of CSV files
Symbol/Char Meaning Operating System
CR[\r] Carriage Return Macintosh
LF[\n] Line Feed UNIX
CR[\r] / LF[\n] Carriage Return / Line Feed MS-DOS, Windows, OS/2
NULL [\0] Null Character Other OSs
As CSV files are text files, while storing them, some types of translations occur- such as
translation of end of line(EOL) character as per the operating system working on it.
Fh = open(“[Link]”, “w”, newline=’’)
Null space in newline will suppress EOL translation
Writing in CSV files
[Link]() Returns a writer object which writes data into CSV files
<writerobject>.writerow() Writes one row of data onto the writer object
<writerobject>.writerow() Writes multiple rows of data onto the writer object
1. Import csv module
2. Open csv file in a file-handle
3. Create writer object
stuwriter= [Link](fh, delimiter= ’|’)
4. Obtain user data and form a python sequence(list or tuple) out of it.
sturec=(11,’Neelam’,79.9)
5. Write python sequence containing user data onto the writer object using
[Link]() or [Link]() functions
[Link](sturec)
6. Close the file
Role of csv writer object
Write a program to create a CSV file to store student data(Rollno, Name,
Marks). Obtain data from user and write 5 records into the file.
import csv
fh=open(“[Link]”,”w”)
stuwriter=[Link](fh)
[Link]([‘Rollno’, ‘Name’, ‘Marks’])
for i in range(5):
print(“Student record”, (i+1))
rollno=int(input(“Enter Roll No:”))
name=input(“Enter Name:”)
marks=float(input(“Enter Marks:”))
sturec=[rollno,name,marks]
[Link](sturec)
[Link]()
The writerows() function
The data of winners of four rounds of a import csv
competitive programming competition is fh=open(“[Link]”,”w”)
given as: cwriter=[Link](fh)
compdata=[
[‘Name’,’Points’, ‘Rank’],
[‘Shradha’, 4500, 23],
[‘Nishchay’, 4800, 31],
[‘Ali’, 4500, 25],
[‘Adi’, 5100, 14],
Write a program to create a csv [Link](compdata)
file([Link]) and write the above [Link]()
data into it.
Reading in CSV files
[Link]()
1. Import csv module
2. Open csv file in a file-handle in read mode
fh=open(“[Link]”,’r’)
3. Create reader object
stureader= [Link](fh, delimiter= ’|’)
4. The reader object stores the parsed data in the form of iterable and thus you can
fetch values using loop, one row at a time.
for rec in stureader:
print(rec)
5. Process the fetched single row of data as required
[Link](sturec)
6. Close the file
The [Link]() function
Write a program to read the records of The [Link] file was created on
[Link] file and display them windows OS where EOL is ‘\r\n’. Modify the
code so that the blank lines for every EOL are
import csv
with open(”[Link]”,’r’) as fh: not displayed.
creader=[Link](fh)
import csv
for rec in creader: with open(”[Link]”,’r’,newline=’\r\n’) as fh:
print(rec) creader=[Link](fh)
for rec in creader:
print(rec)