0% found this document useful (0 votes)
5 views15 pages

Python-CSV Files

This document provides an overview of file handling in Python, specifically focusing on CSV files. It explains the types of files, the importance of backing storage, basic file operations, and how to read from and write to CSV files using the Python csv module. Additionally, it includes examples of functions for appending records, displaying CSV content, and searching for specific records.

Uploaded by

vedkavathiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views15 pages

Python-CSV Files

This document provides an overview of file handling in Python, specifically focusing on CSV files. It explains the types of files, the importance of backing storage, basic file operations, and how to read from and write to CSV files using the Python csv module. Additionally, it includes examples of functions for appending records, displaying CSV content, and searching for specific records.

Uploaded by

vedkavathiya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Notes Class XII CSV File

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.

Why do we need file? We need file because:


• RAM (main storage) is volatile – data and program cannot be stored permanently
• RAM (main storage) has limited capacity

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.

Commonly used backing storage:


1. Magnetic Storage: Internal Hard Disk Drive, Portable Hard Disk, Magnetic Tape and Floppy disk
2. Electronic Storage: Solid State Drive, USB Flash Drive (USB Pen Drive) and SD Card
3. Optical Storage: CD, DVD and Blu-Ray Disc

A file can be stored internally (in the backing storage) as:


• Text file – file stored in the backing storage in human readable format. Text file can be read and edited
with any text editor like Notepad.
• Binary file – file stored in the backing storage in machine readable format. Binary file can be read
and edited with the application (program) that created the binary file.

There are two basic operations in a file:


• Write into a file – data is transferred from variable(s) located in the main storage (RAM) to file(s)
located in the backing storage
• Read from a file – data is transferred from file(s) located in the backing storage to the variable(s)
located in the main storage (RAM)

Three basic steps when working with file in Python:


• Open a file for writing • Open a file for reading
• Write into a file • Read from a file
• Close file • Close file

How to open a file? In Python a file can be opened in two ways:


• Using function open()
Syntax: fileobject=open(filename, mode)
Independent built-in function open() will ensure filename is ready for writing or reading
so that data is transferred between RAM (main storage) and the backing storage.
fileobject is a Python variable
filename name of the file and file name is a string
mode write mode / append mode / read mode and if mode is omitted, default is the
read mode
Example #1: fw=open('ITEM.CSV', 'w', newline="")
fw is the file object (fw – file write)
'ITEM.CSV' is the file name
'w' is the mode, 'w' stands for write mode

Example #2: fa=open('ITEM.CSV', 'a', newline="")


fa is the file object (fa – file append)
'ITEM.CSV' is the file name
'a' is the mode, 'a' stands for append mode

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()

Example #2: fr=open('ITEM.CSV', 'r')


#Open file for read operation
fr.close()
fr is the file object (fr – file read)
'ITEM.CSV' is the file name
'r' is the mode, 'r' stands for read mode

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.

Important functions and methods for Python csv file:


• open() – is a built-in independent function to create a file object and to open a CSV file
• reader() – is a function from CSV module and it will read all the records (all the lines / rows /
records) from a CSV file into an CSV reader object (iterator object)
• writer() – is a function from CSV module and it will create a CSV writer object
• writerow() – is a CSV writer object method and it will write a list (tuple) into a CSV file
• writerows() – is a CSV writer object method and it will write a nested list (nested tuple) into
a CSV file
• delimiter – the default delimiter in a CSV file is comma (,) but using delimiter as an additional
parameter with reader() or with writer() one can specify a single character string as the
delimiter
• close() – is a method from the file object created by open() and it closes a CSV file, but if a
CSV file is opened using keyword with then there is no need to close the file

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:

import csv In the CSV file, default separator


def append(): comma (,) will be replaced by
fobj=open('RESULT.CSV', 'w', newline="") tilde (~). Now CSV file will be
cwobj=csv.writer(fobj) created without any blank line
#OR, cwobj=csv.writer(fobj, delimiter='~')
after every record / row.
n=int(input('Number of Records? '))
for x in range(n): Content of the file CSV file 'RESULT.CSV'
roll=int(input('Roll? ')) will be overwritten by new set of inputs since
name=input('Name? ').upper() the CSV file 'RESULT.CSV' already exits.
marks=float(input('Marks? '))
stu=[roll, name, marks] #stu=(roll, name, marks)
cwobj.writerow(stu)
fobj.close() Call to method cwobj.writerow(stu) is inside the for-loop.
OR,
def append():
with open('RESULT.CSV', 'w', newline="") as fobj:
cwobj=csv.writer(fobj)
Opening a file with keyword with, file
n=int(input('Number of Records? '))
for x in range(n): will be automatically closed after the
roll=int(input('Roll? ')) end of with block. Without keyword
name=input('Name? ').upper() with, if a file is not closed, there will
marks=float(input('Marks? ')) be loss of data.
stu=[roll, name, marks] #stu=(roll, name, marks)
cwobj.writerow(stu)

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)

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 is
for stu in stulist:
tilde (~) instead of default
print(stu[0], stu[1], stu[2], sep='\t')
separator comma (,).
fobj.close()
OR,
def display():
with open('RESULT.CSV') as fobj:
#with open('RESULT.CSV', 'r') as fobj: Read ('r') mode is the default
stulist=csv.reader(fobj) mode. So, mode is optional when
for stu in stulist: a file is opened in read mode.
print(stu[0], stu[1], stu[2])
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 on the screen.

Function to search for roll using a flag variable is given below:


import csv
def searchroll():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
roll=int(input('Roll to Search? '))
Page 5/15
Python Notes Class XII CSV File
#roll= input('Roll to Search? ')
found=0
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print(stu[0], stu[1], stu[2])
found=1
break
fobj.close()
if found==0: print(roll,'not found in the file')
OR,
def searchroll():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
roll=int(input('Roll to Search? '))
#roll=input('Roll to Search? ')
found=False
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print(stu[0], stu[1], stu[2])
found=True
break
if found==0: print(roll,'not found in the file')

Function to search for roll without flag variable is given below:


import csv
def searchroll():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
roll=int(input('Roll to Search? '))
#roll=input('Roll to Search? ')
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print(stu[0], stu[1], stu[2])
break
else:
print(roll,'not found in the file')
fobj.close()
OR,
def searchroll():
with open('RESULT.CSV') as fobj:
stulist=csv.reader(fobj)
roll=int(input('Roll to Search? '))
#roll=input('Roll to Search? ')
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
print(stu[0], stu[1], stu[2])
break
else:
print(roll,'not found in the file')

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 search for marks<33 is given below:


import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
found=0
for stu in stulist:
if float(stu[2])<33.0:
print(stu[0], stu[1], stu[2])
found=1
fobj.close()
if not found: print('No such records found!')
OR,
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
if float(stu[2])<33.0:
print(stu[0], stu[1], stu[2])
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<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 search for marks>=40 and marks<=60 is given below:


import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
found=False
for stu in stulist:
if float(stu[2])>=40.0 and float(stu[2])<=60.0:
#if 40.0<=float(stu[2])<=60.0:
print(stu[0], stu[1], stu[2])
found=True
fobj.close()
if found==0: print('No such records found!')
Page 9/15
Python Notes Class XII CSV File
OR,
import csv
def searchmarks():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
c=0
for stu in stulist:
if float(stu[2])>=40.0 and float(stu[2])<=60.0:
#if 40.0<=float(stu[2])<=60.0:
print(stu[0], stu[1], stu[2])
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 every student using a nested list.


import csv
def editrecords():
fobj=open('RESULT.CSV')
stulist=list(csv.reader(fobj))
for stu in stulist:
stu[2]=float(stu[2])+2
fobj.close()
fobj=open('RESULT.CSV', 'w', newline='')
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
fobj.close()
print('All Records Updated in the File')
OR,
Page 12/15
Python Notes Class XII CSV File
import csv
def editrecords():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=list(csv.reader(fobj))
for stu in stulist: stu[2]=float(stu[2])+2
fobj.seek(0)
fobj.truncate()
cwobj=csv.writer(fobj)
cwobj.writerows(stulist)
#for rec in stulist: cwobj.writerow(rec)
fobj.close()
print('All Records Updated in the File')

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')

Function to delete a particular record using a nested list is given below:


import csv
def delrecord():
fobj=open('RESULT.CSV')
stulist=csv.reader(fobj)
roll=int(input('Input Roll to Delete? '))
#roll=input('Input Roll to Delete? ')
found=False
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
stulist.remove(stu)
#stulist.pop(data.index(stu))
Page 14/15
Python Notes Class XII CSV File
#del stulist[stulist.index(stu)]
found=True
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 found:
print('Record Deleted From the File')
else:
print(roll,'Not Found in the File')
OR,
import csv
def delrecord():
fobj=open('RESULT.CSV', 'r+', newline='')
stulist=csv.reader(fobj)
roll=int(input('Input Roll to Delete? '))
#roll=input('Input Roll to Delete? ')
found=False
for stu in stulist:
if roll==int(stu[0]):
#if roll==stu[0]:
stulist.remove(stu)
#stulist.pop(data.index(stu))
#del stulist[stulist.index(stu)]
found=True
break
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 Deleted From the File')
else:
print(roll,'Not Found in the File')
Please ignore Python script written with blue / gray box. The script and concept of 'r+' mode will
be discussed later.

File Mode Detailed explanation


• Data is transferred from main storage (RAM) to backing storage
Write
• If the file does not exist, a new file is created
('w')
• If the file exists, new set of data overwrites existing data in the file, there will be data loss
• Data is transferred from main storage (RAM) to backing storage
Append
('a') • If the file does not exist, a new file is created
• If the file exists, new set data will be added at the end, there will be no loss of data
• Data is transferred from backing storage to main storage (RAM)
Read
('r') • If the file exists, data stored in the file can be read successfully
• If the file does not exist, a run-time will be triggered

Page 15/15

You might also like