Python CSV Files
Python CSV Files
CSV file
A CSV (Comma Separated Value) file is a text file that stores tabular data in simple text format separated
by a separator. The default separator is comma (,) but any other single character can be used as a separator.
An example of CSV file is given below:
1001,KARAN GHEI,172000,14
1002,BIDISHA JAIN,177000,19
1003,CHANDAN DUA,179000,15
1004,TAHIRA KHAN,178000,16
1005,SUNIL SHARMA,175000,18
Each line in the file stores Code, Name, Basic and Years of an employee. Notice each piece of data is
separated by a comma (, default separator). First line represents header row. But a header row is optional.
If a header row is present, it represents name for every field (column). Every subsequent line after header
row is actual data. CSV files are normally created by programs that handle large amounts of data. They
are a convenient way to export data from spreadsheets and databases as well as import data for further
use. The Python csv module provides functions to write into CSV file and read from CSV file. Generally,
a CSV file has an extension .CSV. But any text file with extension .TXT and containing comma (,)
separated values (or values separated by any other separator) can be open using CSV module.
A Python function is given below showing how to write into a CSV file:
import csv
def append():
fobj=open('RESULT.CSV', 'a')
cwobj=csv.writer(fobj)
n=int(input('No. Records? '))
for x in range(n):
roll=int(input('Roll? '))
name=input('Name? ').upper()
marks=float(input('Marks? '))
stu=[roll, name, marks] #stu=(roll, name, marks)
cwobj.writerow(stu)
fobj.close() Function call cwobj.writerow(stu) is inside the for-loop.
Variable fobj is a file object created with function open(). Function csv.writer(fobj) creates a
CSV writer object cwobj. Variable stu is a list(tuple) containing roll, name and marks.
cwobj.writerow(stu) writes data stored in the list(tuple) stu into the CSV file 'RESULT.CSV' .
CSV file created, will contain records (rows / line of text) in the following format:
Page 1/9
Python Notes Class XII CSV File
1,AAAA,92.2
2,BBBB,78.0
3,CCCC,86.0
4,DDDD,72.0
5,EEEE,84.0
After every record (line), there is a blank line in the CSV file. To remove the blank lines, an additional
parameter is needed in the open() function, open('RESULT.CSV', 'a', newline=''). Edited
function is given below:
import csv
def append():
fobj=open('RESULT.CSV', 'a', newline='')
cwobj=csv.writer(fobj)
#fobj=open('RESULT.CSV', 'a')
#cwobj=csv.writer(fobj, lineterminator='\n')
#OR, cwobj=csv.writer(fobj, delimiter='~') In the CSV file, default
n=int(input('Number of Records? ')) separator comma (,) will
for x in range(n): be replaced by tilde (~).
roll=int(input('Roll? '))
name=input('Name? ').upper()
marks=float(input('Marks? '))
stu=[roll, name, marks] #stu=(roll, name, marks)
cwobj.writerow(stu)
fobj.close() Function call cwobj.writerow(stu) is inside the for-loop.
OR,
import csv
def append():
fobj=open('RESULT.CSV', 'a', newline='')
cwobj=csv.writer(fobj)
n=int(input('Number of Records? '))
stulist=[]
for x in range(n):
roll=int(input('Roll? '))
name=input('Name? ').upper()
marks=float(input('Marks? '))
stu=[roll, name, marks] #stu=(roll, name, marks)
stulist.append(stu) #stulist+=[stu]
cwobj.writerows(stulist)
fobj.close() Function call cwobj.writerows(stulist)
is outside the for-loop.
Function to display a CSV file is given below:
import csv
def display():
fobj=open('RESULT.CSV') #OR, fobj=open('RESULT.CSV', 'r')
stulist=csv.reader(fobj)
#OR, stulist=csv.reader(fobj, delimiter='~')
In the CSV file, separator
for stu in stulist:
is tilde (~) instead of
print(stu[0], stu[1], stu[2], sep='\t')
comma (,).
fobj.close()
Page 2/9
Python Notes Class XII CSV File
Variable fobj is a file object created with function open(). Function csv.reader(fobj) creates a
CVS reader object (iterator object) stulist and using for-loop one can iterates over the object
stulist. Function print() displays the CSV file in a tabular format using tab as a separator.
Function to search for name using flag variable is given below (assuming all names are distinct):
import csv
def searchname():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
name=input('Name to search? ').upper()
found=0
for stu in stulist:
if name==stu[1]:
print(stu[0], stu[1], stu[2], sep='\t')
found=1
break
fobj.close()
if found==0: print(name,'not found in the file')
OR,
Function to search for name without flag variable is given below (assuming all names are distinct):
import csv
def searchname():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
Page 3/9
Python Notes Class XII CSV File
name=input('Name to search? ').upper()
for stu in stulist:
if name==stu[1]:
print(stu[0], stu[1], stu[2], sep='\t')
found=1
break
else:
print(name,'not found in the file')
fobj.close()
Write a function to read and display a CSV file 'RESULT.CSV' and at the end display number of records
where marks>90.
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2], sep='\t')
if float(stu[2])>=90.0: c+=1
fobj.close()
print('Number of Records=',c)
Write a function to read and display a CSV file 'RESULT.CSV' and at the end display number of records
where marks<33.
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2], sep='\t')
if float(stu[2])<33.0: c+=1
fobj.close()
print('Number of Records=',c)
Write a function to read and display a CSV file 'RESULT.CSV' and at the end display number of records
where marks>=40 and marks<=60.
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2], sep='\t')
if float(stu[2])>=40.0 and float(stu[2])<=60.0: c+=1
#if 40.0<=float(stu[2])<=60.0: c+=1
fobj.close()
print('Number of Records=',c)
Function to edit marks of every student using a temporary CSV file is given below:
import csv, os
def editrecords():
frobj=open('RESULT.CSV')
fwobj=open('TEMP.CSV', 'w', newline='')
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
for stu in stulist:
stu[2]=float(stu[2])+5 #marks is increased by 5
cwobj.writerow(stu)
frobj.close()
fwobj.close()
print('All Records Updated in the File')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
Function to edit marks of a particular record using a temporary CSV file is given below:
import csv, os
def editrecords():
frobj=open('RESULT.CSV')
fwobj=open('TEMP.CSV', 'w', newline='')
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
roll=int(input('Input Roll to Edit? '))
found=0
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+5 #marks is increased by 5
print('Record Updated in the File')
found=1
cwobj.writerow(stu)
frobj.close(); fwobj.close()
if found==0: print(roll,'Not found in the file')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
Page 6/9
Python Notes Class XII CSV File
Function to delete a particular record using a temporary CSV file is given below:
import csv, os
def delrecord():
frobj=open('RESULT.CSV')
fwobj=open('TEMP.CSV', 'w', newline='')
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
roll=int(input('Input Roll to Delete? '))
found=0
for stu in stulist:
if roll==int(stu[0]):
print('Record Deleted from the File')
found=1
else:
cwobj.writerow(stu)
frobj.close()
fwobj.close()
if found==0:
print(roll,'Not Found in the File')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
Function to edit marks of every student using a list (without using a temporary file) is given below:
import csv
def editrecords():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
newlist=[]
for stu in stulist:
stu[2]=float(stu[2])+5
newlist+=[stu]
fobj.close()
fobj=open('RESULT.CSV', 'w', newline='')
cwobj=csv.writer(fobj)
cwobj.writerows(newlist)
fobj.close()
print('All Records Updated in the File')
OR,
import csv
def editrecords():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=csv.reader(fobj)
newlist=[]
for stu in stulist:
stu[2]=float(stu[2])+5
newlist+=[stu]
fobj.seek(0)
fobj.truncate()
cwobj=csv.writer(fobj)
cwobj.writerows(newlist)
fobj.close()
print('All Records Updated in the File')
Page 7/9
Python Notes Class XII CSV File
Function to edit marks of a particular record using a list is given below:
import csv
def editrecords():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
roll=int(input('Input Roll to Delete? '))
newlist, found=[], 0
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+5
found=1
newlist+=[stu]
fobj.close()
if found==1:
fobj=open('RESULT.CSV', 'w', newline='')
cwobj=csv.writer(fobj)
cwobj.writerows(newlist)
fobj.close()
print('Record Deleted From the File')
else:
print(roll,'Not Found in the File')
OR,
import csv
def editrecords():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=csv.reader(fobj)
newlist=[]
roll=int(input('Input Roll to Delete? '))
found=0
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+5
found=1
newlist+=[stu]
if found==1:
fobj.seek(0)
fobj.truncate()
cwobj=csv.writer(fobj)
cwobj.writerows(newlist)
print('Record Updated in the File')
else:
print(roll,'Not Found in the File')
fobj.close()
Sorting records of a CSV data file STUDENT.CSV on marks in descending order and displaying the
sorted records on the screen. Every record is stored in the following format: roll,name,marks
import csv
def display():
fobj=open('RESULT.CSV')
slist=list(csv.reader(fobj))
fobj.close()
n=len(slist)
for k in range(1,n):
for x in range(n-k):
if float(slist[x][2])<float(slist[x+1][2]):
slist[x], slist[x+1]=slist[x+1], slist[x]
print('Display Records Sorted on Marks in Descending order')
for stu in slist: print(stu[0], stu[1], stu[2], sep='\t')
Kindly note:
if float(slist[x][2])<float(slist[x+1][2]): sorts on marks in descending order
if slist[x][1]>slist[x+1][1]: sorts on name in ascending order
if int(slist[x][0])>int(slist[x+1][0]): sorts on roll in ascending order
Page 9/9