Python-CSV Files
Python-CSV Files
File: is either data or program stored in a backing storage. A file can be stored in a human readable form,
called text file. A file can be stored in machine readable form, called binary file.
What is backing storage? Backing storage is a storage device where data and programs can be stored
permanently. Until and unless user decides to delete the file from the backing storage, the file will remain
permanently.
Page 1/15
Python Notes Class XII CSV File
Example #3: fr=open('ITEM.CSV', 'r')
#fr=open('ITEM.CSV')
Default mode is read mode.
fr is the file object (fr – file read)
'ITEM.CSV' is the file name
'r' is the mode, 'r' stands for read mode
How to close a file? In Python, a file is closed with close() method of a file object. As discussed earlier,
a file object is created with open() function.
While writing into a file, it ensure that all data has been successfully transferred to the designated file
located in the backing storage. If a file is closed when writing into a file, there will be loss of data. Os, it
mandatory to close a file, writing into a file. When reading from a file, close is optional but it is always a
good practice to close a file. Once a file has been closed, one can neither write nor read from the file.
Syntax: fileobject.close()
File will be closed, no more data transfer between RAM and backing storage
fileobject is a Python variable
Example #1: fw=open('ITEM.CSV', 'w', newline="")
#Open file for write operation
fw.close()
fw is the file object (fw – write read)
'ITEM.CSV' is the file name
'w' is the mode, 'w' stands for write mode
fa=open('ITEM.CSV', 'a', newline="")
#Open file for append operation
fa.close()
When a file is opened, a file object is created. We will discuss three attributes (are members of an object
but not methods) of a file object and they are name, mode and closed.
• Attribute name: name will store the name of the file.
• Attribute mode: made will store the mode of the file.
'w' for write mode, 'a' for append mode and 'r' for read mode (default mode)
• Attribute closed: closed will have value False if the file is open and it will have value True if
the file is closed.
CSV file
A CSV (Comma Separated Values) 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
Page 2/15
Python Notes Class XII CSV File
Each line in the file stores Code, Name, Basic and Years of an employee. 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 opened 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', 'w') A new CSV file 'RESULT.CSV' will be
cwobj=csv.writer(fobj) created since the folder does not contain
n=int(input('No. Records? ')) any file named 'RESULT.CSV'.
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 / lines / records) in the following format:
1,AAAA,92.2
2,BBBB,78.0
3,CCCC,86.0
4,DDDD,72.0
5,EEEE,84.0
Page 3/15
Python Notes Class XII CSV File
After every record (line / row), there is a blank line in the CSV file. This extra blank lines in the CSV file
will trigger run-time error when reading from 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:
To ensure the new data is added at end (without any loss of data), the CSV file has to be opened in append
mode.
def append():
fobj=open('RESULT.CSV', 'a', newline="")
cwobj=csv.writer(fobj)
n=int(input('Number of 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()
OR,
def append():
with open('RESULT.CSV', 'w', newline="") as fobj:
cwobj=csv.writer(fobj)
n=int(input('Number of 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)
Page 4/15
Python Notes Class XII CSV File
OR,
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() Call to method cwobj.writerows(stulist)
OR, is outside the for-loop.
def append():
with open('RESULT.CSV', 'a', newline='') as fobj:
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)
Page 6/15
Python Notes Class XII CSV File
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])
found=1
break
fobj.close()
if found==0: print(name,'not found in the file')
OR,
def searchname():
with open('RESULT.CSV') as fobj:
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])
found=1
break
if found==0: print(name,'not found in the file')
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)
name=input('Name to search? ').upper()
for stu in stulist:
if name==stu[1]:
print(stu[0], stu[1], stu[2])
found=1
break
else:
print(name,'not found in the file')
fobj.close()
OR,
def searchname():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
name=input('Name to Search? ').upper()
for stu in stulist:
if name==stu[1]:
print(stu[0], stu[1], stu[2])
found=1
break
else:
print(name,'not found in the file')
Page 7/15
Python Notes Class XII CSV File
Function to search display all the records and count number of records where for 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])
if float(stu[2])>=90.0: c+=1
fobj.close()
print('Number of Records=',c)
OR,
def searchmarks():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2])
if float(stu[2])>=90.0: c+=1
print('Number of Records=',c)
Function to read all the records and display the records where for marks>=90. At the end display number
of such records found.
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
if float(stu[2])>=90.0:
print(stu[0], stu[1], stu[2])
c+=1
fobj.close()
print('Number of Records=',c)
OR,
def searchmarks():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
c=0
for stu in stulist:
if float(stu[2])>=90.0:
print(stu[0], stu[1], stu[2])
c+=1
print('Number of Records=',c)
Write a function to read the and display the records where marks>90. If no such record is found, then
display an appropriate message.
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
found=False
for stu in stulist:
if float(stu[2])>=90.0:
Page 8/15
Python Notes Class XII CSV File
print(stu[0], stu[1], stu[2])
found=True
fobj.close()
if not found: print('No such records found!')
Function to display 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])
if float(stu[2])<33.0: c+=1
fobj.close()
print('Number of Records=',c)
Function to display 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])
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)
OR,
def searchmarks():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2])
if float(stu[2])>=40.0 and float(stu[2])<=60.0: c+=1
#if 40.0<=float(stu[2])<=60.0: c+=1
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])+2 #marks is increased by 2
cwobj.writerow(stu)
frobj.close()
fwobj.close()
print('All Records Updated in the File')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
OR,
Page 10/15
Python Notes Class XII CSV File
def editrecords():
with open('RESULT.CSV') as frobj,\
open('TEMP.CSV', 'w', newline='') as fwobj:
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
for stu in stulist:
stu[2]=float(stu[2])+2 #marks is increased by 2
cwobj.writerow(stu)
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
print('All Records Updated in the File')
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=False
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+2 #marks is increased by 2
print('Record Updated in the File')
found=True
cwobj.writerow(stu)
frobj.close()
fwobj.close()
if not found: print(roll,'Not found in the file')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
OR,
def editrecords():
with open('RESULT.CSV') as frobj, \
open('TEMP.CSV', 'w', newline='') as fwobj:
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
roll=int(input('Input Roll to Edit? '))
found=False
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+2 #marks is increased by 2
print('Record Updated in the File')
found=True
cwobj.writerow(stu)
if not found: print(roll,'Not found in the file')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
Function to delete a particular record using a temporary CSV file is given below:
import csv, os
def delrecord():
frobj=open('RESULT.CSV')
Page 11/15
Python Notes Class XII CSV File
fwobj=open('TEMP.CSV', 'w', newline='')
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
roll=int(input('Input Roll to Delete? '))
#roll=input('Input Roll to Delete? ')
found=0
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print('Record Deleted from the File')
found=1
else:
cwobj.writerow(stu)
frobj.close()
fwobj.close()
if not found:
print(roll,'Not Found in the File')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
OR,
def delrecord():
with open('RESULT.CSV') as frobj,\
open('TEMP.CSV', 'w', newline='') as fwobj:
cwobj=csv.writer(fwobj)
stulist=csv.reader(frobj)
roll=int(input('Input Roll to Delete? '))
#roll=input('Input Roll to Delete? ')
found=0
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print('Record Deleted from the File')
found=1
else:
cwobj.writerow(stu)
if not found: print(roll,'Not Found in the File')
os.remove('RESULT.CSV')
os.rename('TEMP.CSV', 'RESULT.CSV')
Function to edit marks of a particular record using a nested list is given below:
import csv
def editrecords():
fobj=open('RESULT.CSV')
stulist=list(csv.reader(fobj))
roll=int(input('Input Roll to Edit? '))
found=False
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+2
found=True
print('Record Updated From the File')
break
fobj.close()
fobj=open('RESULT.CSV', 'w', newline='')
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
fobj.close()
if not found: print(roll,'Not Found in the File')
OR,
import csv
def editrecords():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=list(csv.reader(fobj))
roll=int(input('Input Roll to Edit? '))
found=0
for stu in stulist:
if roll==int(stu[0]):
stu[2]=float(stu[2])+2
found=1
print('Record Updated in the File')
break
fobj.seek(0)
fobj.truncate()
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
if not found: print(roll,'Not Found in the File')
fobj.close()
Page 13/15
Python Notes Class XII CSV File
Function to edit marks, where marks is less than 40 using a nested list is given below:
import csv
def editrecords():
fobj=open('RESULT.CSV')
stulist=list(csv.reader(fobj))
found=False
for stu in stulist:
if float(stu[2])<40.0:
stu[2]=float(stu[2])+2
found=True
fobj.close()
fobj=open('RESULT.CSV', 'w', newline='')
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
fobj.close()
if found:
print('Records Updated in the File')
else:
print(roll,'Not Found in the File')
OR,
import csv
def editrecords():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=list(csv.reader(fobj))
found=False
for stu in stulist:
if float(stu[2])<40.0:
stu[2]=float(stu[2])+2
found=True
fobj.seek(0)
fobj.truncate()
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
fobj.close()
if found:
print('Record Updated in the File')
else:
print(roll,'Not Found in the File')
Page 15/15