Python Files
Python Files
Why do we need file? We need file to store data (programs) because RAM (main storage) is volatile –
data and program cannot be stored permanently and 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.
How to close a file? In Python, a file is closed with close() method of a file object created using open().
Method close()ensures that all data are written successfully into a file. When writing into a file (write /
append mode), if a file is not closed, entire data may not be written into the file. There could be loss of
data. So, it is mandatory for the programmer to close a file, when a file is opened in write / append mode.
Syntax: [Link]()
File will be closed, no more data transfer between RAM and the backing storage
fileobject is a Python object which is created with open()
Example #1:
fobj=open('[Link]','w') #opens a file in write mode
#fobj=open('[Link]','a') #opens a file in append mode
[Link]()
fobj is the file object (fw – write read)
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
Example #2:
fobj=open('[Link]','r') #opens a file in read mode
#fobj=open('[Link]') #opens a file in default(read) mode
[Link]()
fobj is the file object
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode
How to write into a text file? In Python data can be written into a text file in two ways:
Using file object method write()
Syntax: [Link](string)
File object method write() will transfer a string into a text file and it returns int.
fileobject is a Python object which is created with open()
string is the data to be written into a file
Example #1:
fobj=open('[Link]', 'w')
s1='3 days weekend because of Easter.\n'
s2='Sunday Test postponed to Monday.\n'
[Link](s1) #writes content of s1 into [Link]
[Link](s2) #writes content of s2 into [Link]
[Link]()
fobj is the file object
When a file is opened, a file object is created. A file object has many methods (functions belonging to an
object) as discussed above for writing into a text file and for reading from a text file. Also, there are other
members available from a file object. Members of an object which is not function is generally called
attribute. File object has few attributes and three attributes are explained below:
Attribute closed: closed will have value False if the file is open and it will have value True if
the file is closed.
Attribute mode: mode will store the mode of the file.
'w' for a text file is opened for write mode
'a' for a text file is opened for append mode
'r' for a text file is opened for read mode (default mode)
'wb' for a binary file is opened for write mode
'ab' for a binary file is opened for append mode
'rb' for a binary file is opened for read mode (default mode)
Attribute name: name will store the name of a file.
Python script is given below showing the use of file object attributes closed, mode and name:
fw=open('[Link]', 'w') #fw=open('[Link]', 'wt')
fr=open('[Link]', 'r') #fr=open('[Link]', 'rt')
f1=open('[Link]', 'ab') #f1=open('[Link]', 'ba')
f2=open('[Link]', 'rb') #f2=open('[Link]', 'rb')
print([Link], [Link], [Link])
print([Link], [Link], [Link])
print([Link], [Link], [Link])
print([Link], [Link], [Link])
[Link](); [Link](); [Link](); [Link]()
print([Link], [Link], [Link])
print([Link], [Link], [Link])
print([Link], [Link], [Link])
print([Link], [Link], [Link])
2. Write a Python program to add following lines in an existing text file '[Link]'.
Costo is part of Regency Group which is among
the foremost retail players in GCC region.
s1=' Costo is part of Regency Group which is among\n'
s2=' the foremost retail players in GCC region.\n’
fw=open('[Link]', 'W')
[Link](s1)
[Link](s2)
[Link]()
Executing the Python program will create a text file '[Link]' and the content of the will be
Costo is part of Regency Group which is among
the foremost retail players in GCC region.
That is, previous content of the text file has been overwritten by new set of data. Now it is important
to remember when a file is opened in write mode ('w'):
If the file does not exist, a new file is created
If the file exists, new set of data will overwrite the existing data in the file, there will be loss
of data
File object method write() will only write a single string into a file. As discussed earlier, one can use
file object method wrilelines() to write a list of string into a file (via buffer). A Python program to
write a list of string into a file is given in the next page.
data=['Costo with its first store in Khaitan has\n',
'positioned itself as a cost-effective\n',
'shopping destination. Costo is all set\n',
'to open its second outlet in Fahaheel.\n']
fw=open('[Link]', 'w')
[Link](data)
[Link]()
OR,
data=['Costo with its first store in Khaitan has\n',
'positioned itself as a cost-effective\n',
'shopping destination. Costo is all set\n',
'to open its second outlet in Fahaheel.\n']
with open('[Link]', 'w') as fw: [Link](data)
3. Write a Python program to read and display a text file '[Link]' using file object method read().
fr=open('[Link]', 'r')
data=[Link]()
print(data)
[Link]()
4. Write a Python program to read a text file '[Link]' using file object method read() but display first
182 characters.
fr=open('[Link]', 'r')
data=[Link](182)
print(data)
[Link]()
5. Write a Python program to read and display a text file '[Link]' using file object method readline().
fr=open('[Link]', 'r')
data=[Link]()
while data:
print([Link]())
data=[Link]()
[Link]()
in GCC region.
Why there a blank line after every line? This is because every line in the text file '[Link]' is
terminated by a new line character ('\n') plus print() function is also add a new line character on
the screen. To remove the blank lines from the output, there are two solutions: either remove the new
line character from the print() function or remove the new line character from the string read from the
file. Edit program without the blank lines is given below:
fr=open('[Link]', 'r')
data=[Link]()
while data:
print([Link]()) #print(data,end='')
data=[Link]()
[Link]()
while loop will execute till data!="" is true. Variable data will be "" (empty string) when nothing
can be read from the file end of the file. Function print([Link]()) – removes all the white
FAIPS, DPS Kuwait Page 8 / 16 ©Bikram Ally
Python Notes Class XII Text File
space (space / tab / new line) characters from the beginning and from the end of the string.
print(data,end='') – does not display the default new line character on the screen.
6. Write a Python program to read and display a text file '[Link]' using file object method readlines().
fr=open('[Link]', 'r')
data=[Link]()
[Link]()
for line in data: print([Link]())
File object method readlines() will read the entire file as a list of strings and store it in a variable
data. for loop displays the data on the screen.
7. Write a Python program to read and display a text file '[Link]' using file object as an iterator.
fr=open('[Link]', 'r')
for line in fr: print([Link]())
[Link]()
8. Write a Python program to read and display a text file '[Link]'. File '[Link]' does not have any
new character in the file.
fr=open('[Link]', 'r')
data=[Link]()
print(data)
[Link]()
OR,
fr=open('[Link]', 'r')
data=[Link]()
print(data)
[Link]()
fr=open('[Link]', 'r')
data1=[Link]() #First [Link]()
data2=[Link]() #Second [Link]()
print(data1)
print(date2)
[Link]()
File [Link] will be displayed once because print(data1) will display the file but
print(data2) will display an empty string, so a blank line will be displayed on the screen. Why?
First [Link]() will read the entire file and the file will be stored as string in the variable data1.
Next, the file will encounter End Of File. What is End Of File? It simply means nothing else is left
to be read. So first [Link]() has read everything from the file, second [Link]() has nothing
to read (beyond end of the file), hence data2 will represent an empty string.
def addlines():
data= [ 'COSTO is a customer driven purchase\n',
'store where customer feedbacks determine\n',
'the future products in the store.\n' ]
fw=open('[Link]', 'a')
[Link](data)
[Link]()
FAIPS, DPS Kuwait Page 10 / 16 ©Bikram Ally
Python Notes Class XII Text File
OR,
def addlines():
line1='COSTO is a customer driven purchase\n'
line2='store where customer feedbacks determine\n',
line3='the future products in the store.\n'
fw=open('[Link]', 'a')
[Link](line1)
[Link](line2)
[Link](line3)
[Link]()
OR,
def addlines():
lines='''COSTO is a customer driven purchase
store where customer feedbacks determine
the future products in the store.\n'''
fw=open('[Link]', 'a')
[Link](lines)
[Link]()
OR,
def addlines():
lines='COSTO is a customer driven purchase\nstore where customer
feedbacks determine\nthe future products in the store.\n'
fw=open('[Link]', 'a')
[Link](lines)
[Link]()
OR,
def addlines():
lines='''COSTO is a customer driven purchase
store where customer feedbacks determine
the future products in the store.\n'''
with open('[Link]', 'a') as fw;
[Link](lines)
def countlines():
fr=open('[Link]', 'r')
c=0
for line in fr:
print([Link]())
c+=1
[Link]()
print('Number of lines=',c)
def countwords():
fr=open('[Link]', 'r')
c=0
for line in fr:
print([Link]())
words=[Link]()
c+=len(words)
[Link]()
print('Number of words=',c)
OR,
def countwords():
fr=open('[Link]', 'r')
FAIPS, DPS Kuwait Page 11 / 16 ©Bikram Ally
Python Notes Class XII Text File
data=[Link]()
[Link]()
print([Link]())
words=[Link]()
print('Number of words=',len(words))
def countcharacters():
fr=open('[Link]', 'r')
c=0
for line in fr:
print([Link]())
c+=len(line)
[Link]()
print('Number of characters=',c)
OR,
def countcharacters():
fr=open('[Link]', 'r')
data=[Link]()
[Link]()
print([Link]())
print('Number of characters=',len(data))
def countupperlowerdigit():
fr=open('[Link]', 'r')
c1=c2=c3=0
for line in fr:
print([Link]())
if ch>='A' and ch<='Z': c1+=1
#if 'A'<=ch<='Z': c1+=1
#if [Link](): c1+=1
elif ch>='a' and ch<='z': c2+=1
#elif 'a'<=ch<='z': c2+=1
#elif [Link](): c2+=1
elif ch>='0' and ch<='9': c3+=1
#elif '0'<=ch<='9': c3+=1
#elif [Link](): c3+=1
[Link]()
print('Number of Uppercase=',c1)
print('Number of Lowercase=',c2)
print('Number of Digits =',c3)
def countspecial():
fr=open('[Link]', 'r')1
data=[Link]()
[Link]()
print([Link]())
c=0
for ch in data:
if [Link]()==False: c+=1
#if not [Link](): c+=1
print('Number of Special characters=',c)
OR,
def countspecialwhitespace():
fr=open('[Link]', 'r')
FAIPS, DPS Kuwait Page 12 / 16 ©Bikram Ally
Python Notes Class XII Text File
data=[Link]()
[Link]()
print([Link]())
c1=c2=0
for ch in data:
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': c1+=1
#if [Link](): c1+=1
if ch==' ' or ch=='\t' or ch=='\n': c2+=1
#if ch in ' \t\n': c2+=1
print('Number of Special characters=',len(dat)-c1)
print('Number of White-space characters=',c2)
OR,
def countspecialwhitespace():
fr=open('[Link]', 'r')
data=[Link]()
[Link]()
print([Link]())
c1=c2=0
for ch in data:
if not ('A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9'): c1+=1
'''
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': pass
else: c1+=1
'''
if ch==' ' or ch=='\t' or ch=='\n': c2+=1
#if ch in ' \t\n': c2+=1
print('Number of Special characters=',c1)
print('Number of White-space characters=',c2)
while True:
print('1. Append Lines')
print('2. Count Lines')
print('3. Count Words')
print('4. Count Number of Characters')
print('5. Count Uppercase, Lowercase & Digit')
print('6. Count Special & White-space Characters')
print('0. Exit')
ch=input('Choice[0-5]? ')
if ch=='1': addlines()
elif ch=='2': countlines()
elif ch=='3': countwords()
elif ch=='4': countcharacters()
elif ch=='5': countupperlowerdigit()
elif ch=='6': countspecialwhitespace()
elif ch=='0': break
Write a Python function to read and display a text file [Link] on the screen. At the end display
number of uppercase vowels and number of lowercase vowels present in the file.
def countvowels():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
c1=c2=0
FAIPS, DPS Kuwait Page 13 / 16 ©Bikram Ally
Python Notes Class XII Text File
for ch in mytext:
if ch in 'AEIOU': c1+=1
if ch in 'aeiou': c2+=1
print('Uppercase vowels=', c1)
print('Lowercase vowels=', c2)
Write a Python function to read and display a text file [Link] on the screen. At the end display
number of uppercase consonants, number of uppercase vowels, number of number of lowercase
consonants, number of lowercase vowels present in the file.
def countconsonantsvowels():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
c1=c2=c3=c4=0
for ch in mytext:
if 'A'<=ch<='Z': #if ch>='A' and ch<='Z':
#if [Link]():
if ch in 'AEIOU': c1+=1
else: c2+
if 'a'<=ch<='z': #if ch>='a' and ch<='z':
#if [Link]():
if ch in 'aeiou': c3+=1
else: c4+=1
print('Uppercase vowels=', c1)
print('Uppercase consonants=', c2)
print('Lowercase vowels=', c3)
print('Lowercase consonants=', c4)
Write a Python function to display the text file [Link] on the screen. At end display number of
times 'THE' appear in the file (count ignoring case).
def countword():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
wordlist=[Link]()
c=0
for word in wordlist:
if [Link]()=='THE': c+=1
print('"THE" appears=', c)
Write a Python function to display the text file [Link] on the screen. At end display number words
either starting with 'A'/'a' or starting with 'T'/'t' present in the text file.
def countword():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
wordlist=[Link]()
c=0
for word in wordlist:
if word[0] in 'AaTt': c+=1
print('Words starting with "A/a/T/t"=', c)
FAIPS, DPS Kuwait Page 14 / 16 ©Bikram Ally
Python Notes Class XII Text File
Write a Python function to display the text file [Link] on the screen. At end display number words
either ending with 'E'/'e' or ending with 'I'/'i' present in the text file.
def countword():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
wordlist=[Link]()
c=0
for word in wordlist:
if word[-1] in 'EeIi': c+=1
print('Words ending with "E/e/I/i"=', c)
Write a Python function to display the text file [Link] on the screen. At end display number words
containing at least two vowels present in the text file (ignore case when counting vowels).
def countword():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
wordlist=[Link]()
c1=0
for word in wordlist:
c2=0
for ch in word:
if [Link]() in 'AEIOU': c1+=1
#if [Link]() in 'aeiou': c1+=1
if c2>1: c1+=1
print('Number of words having at least 2 vowels=', c1)
Write a Python function to display the text file [Link] on the screen. At end display number words
starting with a vowel and ending with a vowel present in the text file (ignore case when counting vowels).
def countword():
fobj=open('[Link]')
mytext=[Link]()
[Link]()
print(mytext)
wordlist=[Link]()
c=0
for word in wordlist:
ch1, ch2=word[0].upper(), word[-1].upper()
#ch1, ch2=word[0].lower(), word[-1].lower()
if ch1 in 'AIEOU' and ch2 in 'AEIOU': c+=1
#if ch1 in 'aieou' and ch2 in 'AEIOU': c+=1
print('Words starting with vowel and ending with vowel=', c)
Write a Python function to read and display the text file [Link] on the screen. At end display
number of lines not ending with vowel in the text file (ignore case when checking for vowel).
def countline():
fobj=open('[Link]')
c=0
for line in fobj:
print([Link]())
if line[-1].upper() not in 'AEIOU': c+=1
FAIPS, DPS Kuwait Page 15 / 16 ©Bikram Ally
Python Notes Class XII Text File
#if line[-1].lower() not in 'aeiou': c+=1
#if line[-1] not in 'AEIOUaeiou': c+=1
[Link]()
print('Number of lines not ending with vowel=', c)
Write a Python function to read and display the text file [Link] on the screen. At end display
number of alphabets present in every line.
def countline():
fobj=open('[Link]')
for line in fobj:
c=0
for ch in line:
if 'A'<=ch<='Z' or 'a'<=ch<='z': c+=1
#if ch>='A' and ch<='Z' or ch>='a' and ch<='z': c+=1
#if [Link](): c+=1
print([Link](), c)
[Link]()
Write a Python function to display the text file [Link] on the screen. At end display number of
digits and number of special characters present in every line.
def countline():
fobj=open('[Link]')
for line in fobj:
c1=c2=0
for ch in line:
if '0'<=ch<='9': c1+=1
#if ch>='0' and ch<='9': c1+=1
#if [Link](): c1+=1
if [Link]()==False: c2+=1
#if not [Link](): c2+=1
#if not ('A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9'): c2+=1
'''
if 'A'<=ch<='Z' or 'a'<=ch<='z' or '0'<=ch<='9': pass
else: c2+=1
'''
print([Link](), c1, c2)
[Link]()
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('[Link]', 'r')
#fr=open('[Link]')
Default mode is read mode.
fr is the file object (fr – file read)
'[Link]' 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: [Link]()
File will be closed, no more data transfer between RAM and backing storage
fileobject is a Python variable
Example #1: fw=open('[Link]', 'w', newline="")
#Open file for write operation
[Link]()
fw is the file object (fw – write read)
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
fa=open('[Link]', 'a', newline="")
#Open file for append operation
[Link]()
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('[Link]', 'w') A new CSV file '[Link]' will be
cwobj=[Link](fobj) created since the folder does not contain
n=int(input('No. Records? ')) any file named '[Link]'.
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)
[Link](stu)
[Link]() Function call [Link](stu) is inside the for-loop.
Variable fobj is a file object created with function open(). Function [Link](fobj) creates a
CSV writer object cwobj. Variable stu is a list(tuple) containing roll, name and marks.
[Link](stu) writes data stored in the list(tuple) stu into the CSV file '[Link]' .
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('[Link]', '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('[Link]', 'a', newline="")
cwobj=[Link](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)
[Link](stu)
[Link]()
OR,
def append():
with open('[Link]', 'w', newline="") as fobj:
cwobj=[Link](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)
[Link](stu)
Page 4/15
Python Notes Class XII CSV File
OR,
def append():
fobj=open('[Link]', 'a', newline='')
cwobj=[Link](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)
[Link](stu) #stulist+=[stu]
[Link](stulist)
[Link]() Call to method [Link](stulist)
OR, is outside the for-loop.
def append():
with open('[Link]', 'a', newline='') as fobj:
cwobj=[Link](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)
[Link](stu) #stulist+=[stu]
[Link](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('[Link]')
stulist=[Link](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
[Link]()
if found==0: print(name,'not found in the file')
OR,
def searchname():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
stulist=[Link](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')
[Link]()
OR,
def searchname():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
stulist=[Link](fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2])
if float(stu[2])>=90.0: c+=1
[Link]()
print('Number of Records=',c)
OR,
def searchmarks():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
stulist=[Link](fobj)
c=0
for stu in stulist:
if float(stu[2])>=90.0:
print(stu[0], stu[1], stu[2])
c+=1
[Link]()
print('Number of Records=',c)
OR,
def searchmarks():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
stulist=[Link](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
[Link]()
if not found: print('No such records found!')
Function to display CSV file '[Link]' and at the end display number of records where marks<33.
import csv
def searchmarks():
fobj=open('[Link]')
stulist=[Link](fobj)
c=0
for stu in stulist:
print(stu[0], stu[1], stu[2])
if float(stu[2])<33.0: c+=1
[Link]()
print('Number of Records=',c)
Function to display CSV file '[Link]' and at the end display number of records where marks>=40
and marks<=60.
import csv
def searchmarks():
fobj=open('[Link]')
stulist=[Link](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
[Link]()
print('Number of Records=',c)
OR,
def searchmarks():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
fwobj=open('[Link]', 'w', newline='')
cwobj=[Link](fwobj)
stulist=[Link](frobj)
for stu in stulist:
stu[2]=float(stu[2])+2 #marks is increased by 2
[Link](stu)
[Link]()
[Link]()
print('All Records Updated in the File')
[Link]('[Link]')
[Link]('[Link]', '[Link]')
OR,
Page 10/15
Python Notes Class XII CSV File
def editrecords():
with open('[Link]') as frobj,\
open('[Link]', 'w', newline='') as fwobj:
cwobj=[Link](fwobj)
stulist=[Link](frobj)
for stu in stulist:
stu[2]=float(stu[2])+2 #marks is increased by 2
[Link](stu)
[Link]('[Link]')
[Link]('[Link]', '[Link]')
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('[Link]')
fwobj=open('[Link]', 'w', newline='')
cwobj=[Link](fwobj)
stulist=[Link](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
[Link](stu)
[Link]()
[Link]()
if not found: print(roll,'Not found in the file')
[Link]('[Link]')
[Link]('[Link]', '[Link]')
OR,
def editrecords():
with open('[Link]') as frobj, \
open('[Link]', 'w', newline='') as fwobj:
cwobj=[Link](fwobj)
stulist=[Link](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
[Link](stu)
if not found: print(roll,'Not found in the file')
[Link]('[Link]')
[Link]('[Link]', '[Link]')
Function to delete a particular record using a temporary CSV file is given below:
import csv, os
def delrecord():
frobj=open('[Link]')
Page 11/15
Python Notes Class XII CSV File
fwobj=open('[Link]', 'w', newline='')
cwobj=[Link](fwobj)
stulist=[Link](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:
[Link](stu)
[Link]()
[Link]()
if not found:
print(roll,'Not Found in the File')
[Link]('[Link]')
[Link]('[Link]', '[Link]')
OR,
def delrecord():
with open('[Link]') as frobj,\
open('[Link]', 'w', newline='') as fwobj:
cwobj=[Link](fwobj)
stulist=[Link](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:
[Link](stu)
if not found: print(roll,'Not Found in the File')
[Link]('[Link]')
[Link]('[Link]', '[Link]')
Function to edit marks of a particular record using a nested list is given below:
import csv
def editrecords():
fobj=open('[Link]')
stulist=list([Link](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
[Link]()
fobj=open('[Link]', 'w', newline='')
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
if not found: print(roll,'Not Found in the File')
OR,
import csv
def editrecords():
fobj=open('[Link]', 'r+', newline='')
stulist=list([Link](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
[Link](0)
[Link]()
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
if not found: print(roll,'Not Found in the File')
[Link]()
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('[Link]')
stulist=list([Link](fobj))
found=False
for stu in stulist:
if float(stu[2])<40.0:
stu[2]=float(stu[2])+2
found=True
[Link]()
fobj=open('[Link]', 'w', newline='')
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
if found:
print('Records Updated in the File')
else:
print(roll,'Not Found in the File')
OR,
import csv
def editrecords():
fobj=open('[Link]', 'r+', newline='')
stulist=list([Link](fobj))
found=False
for stu in stulist:
if float(stu[2])<40.0:
stu[2]=float(stu[2])+2
found=True
[Link](0)
[Link]()
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
if found:
print('Record Updated in the File')
else:
print(roll,'Not Found in the File')
Page 15/15
Python Notes Class XII Exception
Whenever one writes a program, there are possibilities of error – it will extremely difficult to write an
error free code. A Python program (script) may have following types of error:
Syntax error – when the rule of the programing language is violated. Before the execution of program,
Python checks for syntax error.
Run-time error – error triggered during the execution of program causing the program to halt
abruptly. Run-time error is triggered because the program encounters unexpected data during the run-
time. An error message is displayed by Python after a run-time error. Every run-time error has a name.
Logical error – most difficult error to detect. Gives unexpected output / result during the run-time
because of flaw in the design or flaw in the logic. Logical error may trigger run-time error.
Value Error
import math
x=eval(input('Value / Expression / Variable Name? '))
y=[Link](x)
print(y)
Index Error
alist=[23,67,45,74]
print(alist[5])
In Python all the run-time errors are called exception. Very few exceptions can be eliminated by using an
if-else statement. So, Python provides an alternative way to handle an exception. Using try statement with
except clause one can handle any exception. try-except can be used in the following way:
Syntax #1
try:
Action1
except:
Action2
[else: Action3]
[finally: Action4]
try, except, else and finally are all keywords. A try statement must have at least one except clause.
else clause and finally clauses are optional.
Action after try may trigger an exception. If Action1 after try triggers an exception, then control
jumps to except clause and Action2 is executed. If Action1 after try does not trigger any exception,
then control jumps to else clause and Action3 is executed. finally clause is always executed, whether
Action1 triggers an exception or not.
x=input('Number? ')
try:
y=100/eval(x)
print(y)
As discussed earlier, finally clause always get executed, whether exception is triggered or not. Edited
Python script with finally clause is given below:
x=input('Number? ')
try:
y=100/eval(x)
except:
print('Error')
else:
print('Quotient=',y)
finally:
print('End of script')
Syntax #2
try:
Action1
except exception1:
Action2
except exception2:
Action3
:
[else: Action4]
[finally: Action5]
Only difference in the second syntax, after the except clause, predefined Python exception are handled
separately. Modified Python script is given below:
Python function to append list type data (every record is a list) in a binary data file type is given below:
import pickle
def addrec():
fobj=open('[Link]', 'ab')
for k in range(5):
code:int(input('Code? ')) Variable emp is a list.
name:input('Name? ')
bsal:float(input('BSal? '))
emp=[code, [Link](), bsal]
#emp=(code, [Link](), bsal)
[Link](emp, fobj)
[Link]() Variable emp is a tuple.
Variable fobj is a binary data file object created with open(). File mode contains 2-characters string.
Letter 'a' for append mode and letter 'b' for binary. If a binary file is to be opened in write mode,
then letter 'w' will replace letter 'a'. Data to be written into the binary is a list emp. Statement
[Link](emp, fobj) writes a record into a binary file data file. One record is written at a time
in the binary data file. A binary data file can store dictionary type data (every record is dictionary type)
also. Python function to append dictionary type data (every record is a dictionary) in a binary data file
type is given below:
import pickle
def addrec():
fobj=open('[Link]', 'ab')
for k in range(5):
code:int(input('Code? '))
name:input('Name? ') Variable emp is a dictionary.
bsal:float(input('BSal? '))
emp={'co':code, 'na':[Link](), 'bs':bsal}
[Link](emp, fobj)
[Link]()
Page 1/18
Python Notes Class XII Binary File
Python function to read and display a binary data file containing list type data (every record is a list) is
given below:
import pickle
def showrec():
fobj=open('[Link]', 'rb')
while Tue: Variable emp is a list.
try:
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
except:
break
[Link]()
OR,
import pickle
def showrec():
fobj=open('[Link]', 'rb')
try: Variable emp is a list.
while Tue:
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
except:
pass
[Link]()
Variable fobj is a binary data file object created with open(). File mode contains 2-characters string.
Letter for 'r' read mode and letter 'b' for binary. Statement emp=[Link](fobj) reads a
record from the binary file stores data in a list type variable emp. Unlike other programming languages,
Python does not have the concept of end of file (eof) when reading from the file. An infinite while loop
is used to read every record from the binary data file and then display the record because it will be
impossible to remember number of dump() operations. Reading beyond the end of the file, will trigger
a run-time error (exception), because [Link]() fails to a record from the binary data file. When
an exception is triggered in the try part, the program control jumps to except part. In the except
part, keyword break will terminate while loop. As discussed earlier, a binary data may contain dictionary
type data. Python function to read and display a binary data file containing dictionary type data (every
record is a dictionary) is given below:
import pickle
def showrec():
fobj=open('[Link]', 'rb') Variable emp is a dictionary.
while True:
try:
emp=[Link](fobj)
print(emp['co'],emp['na'],emp['bs'],sep='\t')
except:
break
[Link]()
OR,
import pickle
def showrec():
fobj=open('[Link]', 'rb') Variable emp is a dictionary.
try:
while True:
emp=[Link](fobj)
print(emp['co'],emp['na'],emp['bs'],sep='\t')
Page 2/18
Python Notes Class XII Binary File
except:
pass
[Link]()
Kindly note: number of load() must match number dump() when reading from a binary data file.
Since it impossible to remember the count, try-except is used to read from a binary file without
triggering any run-time (exception) error. Record in a binary data file can be stored either as a list type
(tuple) type or a dictionary type or a nested list (tuple) type or a list of dictionary type, but hence forth,
all the binary data file functions will assume that a record is stored as a list type in the binary data file.
Function to search for code in a binary data file containing list type data.
import pickle
def searchcode():
code=int(input('Code to Search? '))
fobj=open('[Link]', 'rb')
found=0
while True:
try:
emp=[Link](fobj)
if code==emp[0]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
break
[Link]()
if found==0: print(code, 'not found in the file')
OR,
import pickle
def searchcode():
code=int(input('Code to Search? '))
fobj=open('[Link]', 'rb')
found=0
try:
while True:
emp=[Link](fobj)
if code==emp[0]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
pass
[Link]()
if found==0: print(code, 'not found in the file')
Function to search for name in a binary data file containing list type of data.
import pickle
def searchname():
name=input('Name to Search? ').upper()
fobj=open('[Link]', 'rb')
found=0
while True:
try:
emp=[Link](fobj)
Page 3/18
Python Notes Class XII Binary File
if [Link]()==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
break
[Link]()
if found==0: print(name, 'not found in the file')
OR,
import pickle
def searchname():
name=input('Name to Search? ').upper()
fobj=open('[Link]', 'rb')
found=0
try:
while True:
emp=[Link](fobj)
if [Link]()==emp[1]:
print(emp[0],emp[1],emp[2],sep='\t')
found=1
break
except:
pass
[Link]()
if found==0: print(name, 'not found in the file')
Function to search for salary>150000 and at the end display number of such records found in the binary
data file containing list type of data.
import pickle
def searchbsal():
fobj=open('[Link]', 'rb')
c=0
while True:
try:
emp=[Link](fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
break
[Link]()
print('Number of Records=',c)
OR,
import pickle
def searchbsal():
fobj=open('[Link]', 'rb')
c=0
try:
while True:
emp=[Link](fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
c+=1
except:
Page 4/18
Python Notes Class XII Binary File
pass
[Link]()
print('Number of Records=',c)
Function to search for salary>150000. If no such record is found then display an appropriate message.
import pickle
def searchbsal():
fobj=open('[Link]', 'rb')
found=False
while True:
try:
emp=[Link](fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
found=True
except:
break
[Link]()
if not found: print('No Records Found in the File')
OR,
import pickle
def searchbsal():
fobj=open('[Link]', 'rb')
found=False
try:
while True:
emp=[Link](fobj)
if emp[2]>150000.0:
print(emp[0],emp[1],emp[2],sep='\t')
found=True
except:
pass
[Link]()
if not found: print('No Records Found in the File')
Function to edit all the records (increase bsal by 5000) in a binary data file containing list type of data
using a temporary file.
import pickle, os
def editallrecs():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
while True:
try:
emp=[Link](frobj)
emp[2]+=5000 Every employee's bsal is increased by 5000.
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
[Link]('[Link]')
[Link]('[Link]','[Link]')
Page 5/18
Python Notes Class XII Binary File
Function to edit all the records (increase bsal by 5000) in a binary data file containing list type of data
using a nested list.
import pickle
def editallrecs():
fobj=open('[Link]', 'rb')
elist=[]
while True:
try:
emp=[Link](fobj) Every employee's bsal is increased by 5000.
emp[2]+=5000
[Link](emp) #elist+=[emp]
except:
break
[Link]()
fobj=open('[Link]', 'wb')
for rec in elist: [Link](rec, fobj)
[Link]()
Function to edit a particular record (by inputting employee code) in a binary data file containing list
type of data using a temporary file.
import pickle, os
def editcode():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to Edit? '))
found=False
while True:
try:
emp=[Link](frobj)
if code==emp[0]: Particular employee's bsal is increased by 5000.
emp[2]+=5000
found=True
print('Record Updated in the File!')
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
remove('[Link]')
rename('[Link]','[Link]')
if not found: print(code, 'Not found in the File')
Function to edit a particular record (by inputting employee code) in a binary data file containing list
type of data using a nested list.
import pickle
def editallrecs():
fobj=open('[Link]', 'rb')
code=int(input('Code to Edit? '))
found=False
elist=[]
while True:
try:
if code==emp[0]: Every employee's bsal is increased by 5000.
emp[2]+=5000
Page 6/18
Python Notes Class XII Binary File
found=True
print('Record Updated in the File!')
[Link](emp) #elist+=[emp]
except:
break
[Link]()
fobj=open('[Link]', 'wb')
for rec in elist: [Link](rec, fobj)
[Link]()
if not found: print(code, 'Not found in the File')
Function to edit records (for a given condition) in a binary data file containing list type of data using a
temporary file.
import pickle, os
def editcode():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
found=False
while True:
try:
emp=[Link](frobj)
if emp[2]<100000: Employee's bsal is increased by 5000.
emp[2]+=5000
found=True
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
remove('[Link]')
rename('[Link]','[Link]')
if found:
print('Record(s) Updated in the File!')
else:
print('No Records found in the File')
Function to edit records (for a given condition) in a binary data file containing list type of data using a
using a nested list.
import pickle
def editallrecs():
fobj=open('[Link]', 'rb')
found=False
elist=[]
while True:
try:
if emp[2]<100000: Employee's bsal is increased by 5000.
emp[2]+=5000
found=True
[Link](emp) #elist+=[emp]
except:
break
[Link]()
fobj=open('[Link]', 'wb')
for rec in elist: [Link](rec, fobj)
Page 7/18
Python Notes Class XII Binary File
[Link]()
if found:
print('Record(s) Updated in the File!')
else:
print('No Records found in the File')
Function to delete a record from a binary data file (containing list type of data) using a temporary file.
import pickle, os
def deletecode():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to Edit? '))
found=False
while True:
try:
emp=[Link](frobj)
if code==emp[0]:
found=True
else:
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
[Link]('[Link]')
[Link]('[Link]','[Link]')
if found==1:
print('Record Deleted From the File')
else:
print(code, 'No Records Found in the File')
Function to delete a record from a binary data file (containing list type of data) using a nested list.
import pickle
def deletecode():
fobj=open('[Link]', 'rb')
code=int(input('Code to Edit? '))
found=False
elist=[]
while True:
try:
emp=[Link](fobj)
if code==emp[0]:
found=True
else:
[Link](emp) elist+=[emp]
except:
break
[Link]()
fobj=open('[Link]', 'wb')
for rec in elist: [Link](rec, fobj)
if found==1:
print('Record Deleted From the File')
else:
print(code, 'No Records Found in the File')
Page 8/18
Python Notes Class XII Binary File
import pickle
from os import remove, rename
def addrecords():
n=int(input('Number of Records? '))
fobj=open('[Link]', 'ab')
for k in range(n):
code=int(input('Code? '))
name=input('Name? ').upper()
bsal=float(input('BSal? '))
emp=[code, [Link](), bsal, 0.2*bsal]
[Link](emp, fobj)
[Link]()
def showrecords():
fobj=open('[Link]', 'rb')
while True:
try:
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
except:
break
[Link]()
def findrecord():
while True:
print('-- Search Menu --')
print('1. Search by Code')
print('2. Search by Name')
print('3. Search by Basic Greater')
print('4. Search by Basic in Range')
print('5. Search by Basic Lesser')
print('0. To Return')
cho=input('Choice[0-5]? ')
found=0
if cho=='1':
fobj=open('[Link]', 'rb')
code=int(input('Code to search? '))
while True:
try:
emp=[Link](fobj)
if code==emp[0]:
print('Employee details')
print('Code =', emp[0])
print('Name =', emp[1])
print('BSal =', emp[2])
print('HRA =', emp[3])
found=1
break
except:
break
[Link]()
if found==0: print('Code =',code,'Not found in the file!')
elif cho=='2':
fobj=open('[Link]', 'rb')
Page 9/18
Python Notes Class XII Binary File
name=input('Name to search? ')
while True:
try:
emp=[Link](fobj)
if [Link]()==emp[1]:
print('Employee details')
print('Code =', emp[0])
print('Name =', emp[1])
print('BSal =', emp[2])
print('HRA =', emp[3])
found=1
break
except:
break
if found==0: print('Code =',code,'Not found in the file!')
elif cho=='3':
fobj=open('[Link]', 'rb')
while True:
try:
emp=[Link](fobj)
if emp[2]>150000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
break
[Link]()
if found==0: print('No Records Found in the File!')
elif cho=='4':
fobj=open('[Link]', 'rb')
while True:
try:
emp=[Link](fobj)
if emp[2]>=125000 and emp[2]<=175000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
break
[Link]()
if found==0: print('No Records Found in the File!')
if found==0:
print('No Records Found in the File!')
elif cho=='5':
fobj=open('[Link]', 'rb')
while True:
try:
emp=[Link](fobj)
if emp[2]<175000:
print(emp[0],emp[1],emp[2],emp[3],sep='\t')
found=1
except:
break
if found==0: print('No Records Found in the File!')
elif cho=='0': break
Page 10/18
Python Notes Class XII Binary File
def editrecord():
while True:
print('-- Edit Menu --')
print('1. Edit One Record')
print('2. Edit All Records')
print('0. Return')
cho=input('Choice[0-2]? ')
if cho=='1':
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to edit? '))
found=0
while True:
try:
emp=[Link](frobj)
if code==emp[0]:
print('Current Bsal=',emp[2])
emp[2]=float(input('New BSal? '))
emp[3]=0.2*emp[2]
found=1
print('Record with code =',code,'is updated!')
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
if found==0: print('Code =',code,'not found in the file!')
remove('[Link]')
rename('[Link]', '[Link]')
elif cho=='2':
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
while True:
try:
emp=[Link](frobj)
emp[2]+=10000
emp[3]=0.2*emp[2]
[Link](emp, fwobj)
except:
break
[Link]()
[Link]()
print('All records are updated!')
remove('[Link]')
rename('[Link]', '[Link]')
elif cho=='0': break
def delrecord():
while True:
print('-- Delete Menu --')
print('1. Delete by code')
print('2. Delete by name')
print('0. Return')
cho=input('Choice[0-2]? ')
Page 11/18
Python Notes Class XII Binary File
if cho=='1':
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to delete? '))
found=0
while True:
try:
emp=[Link](frobj)
if code==emp[0]:
found=1
print('Record with code =',code,'is deleted!')
else:
[Link](emp, fwobj)
except: break
[Link]()
[Link]()
if found==0: print('Code =',code,'not found in the file!')
remove('[Link]')
rename('[Link]', '[Link]')
elif cho=='2':
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
name=input('Name to delete? ').upper()
found=0
while True:
try:
emp=[Link](frobj)
if name==emp[1]:
found=1
print('Record with name =',name,'is deleted!')
else:
[Link](emp, fwobj)
except: break
[Link]()
[Link]()
if found==0: print('Name =',name,'not found in the file!')
remove('[Link]')
rename('[Link]', '[Link]')
elif cho=='0': break;
while True:
print('-- Main Menu --')
print('1. Add Records')
print('2. Show Records')
print('3. Search Record')
print('4. Edit Record')
print('5. Delete Record')
print('0. Exit')
ch=input('Choice[0-6]? ')
if ch=='1': addrecords()
elif ch=='2': showrecords()
elif ch=='3': findrecord()
elif ch=='4': editrecord()
elif ch=='5': delrecord()
elif ch=='0': break
Page 12/18
Python Notes Class XII Binary File
We have used a list to store (write / append) a record in a binary file. But instead of using a list, we may
use a dictionary to store (write / append) a record in a binary file. Functions are given below using
dictionary for appending records in a binary file, reading records from a binary file, searching for
records(s) stored in a binary file, updating record(s) stored in a binary file and deleting record(s) from a
binary.
import pickle, os
def addemprec():
fobj=open('[Link]', 'ab')
n=int(input('Number of records? '))
for x in range(n):
emp={
'code':int(input('Code? ')),
'name':input('Name? ').upper(),
'bsal':float(input('BSal? '))
}
[Link](emp, fobj)
[Link]()
def reademprec():
fobj=open('[Link]', 'rb')
while True:
try:
rec=[Link](fobj)
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
except: break
[Link]()
def searchcode():
fobj=open('[Link]', 'rb')
code=int(input('Code to Search? '))
found=0
while True:
try:
rec=[Link](fobj)
if code==rec['code']:
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
found=1
break
except: break
[Link]()
if found==0: print(code, 'Not Found in the File!!')
def searchbsal():
fobj=open('[Link]', 'rb')
found=0
while True:
try:
rec=[Link](fobj)
if 120000.0<=rec['bsal']<=140000.0:
print(rec['code'], rec['name'], rec['bsal'], sep='\t')
found=1
except: break
[Link]()
if found==0: print('No Record Found in the File!!')
Page 13/18
Python Notes Class XII Binary File
def updatebsalall():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
while True:
try:
rec=[Link](frobj)
rec['bsal']+=5000
[Link](rec, fwobj)
except: break
[Link]()
[Link]()
[Link]('[Link]')
[Link]('[Link]','[Link]')
print('All records have been updated!!')
def updatebsal():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to Edit? '))
found=0
while True:
try:
rec=[Link](frobj)
if code==rec['code']:
rec['bsal']+=5000
found=1
print('Record Updated!')
[Link](rec, fwobj)
except: break
[Link]()
[Link]()
[Link]('[Link]')
[Link]('[Link]','[Link]')
if found==0: print(code, 'Not Found in the File!!')
def deleterec():
frobj=open('[Link]', 'rb')
fwobj=open('[Link]', 'wb')
code=int(input('Code to Delete? '))
found=0
while True:
try:
rec=[Link](frobj)
if code==rec['code']:
found=1
print('Record Deleted!')
else:
[Link](rec, fwobj)
except: break
[Link]()
[Link]()
[Link]('[Link]')
[Link]('[Link]','[Link]')
if found==0: print(code, 'Not Found in the File!!')
Page 14/18
Python Notes Class XII Binary File
Instead of using a list or a dictionary to store records in a binary file, we may use a nested list to store
records in a binary. Advantages of nested list to store records in binary file are:
All the records can be stored using single dump() function
All the records can be read using single load() function
Complete menu driven program is given below showing how to use nested list to store / read / search /
edit / delete records using nested list.
import pickle
def addrecord():
fobj=open('[Link]', 'ab+')
if [Link]()==0:
stulist=[]
else:
[Link](0)
stulist=[Link](fobj)
n=int(input('Records to Append? '))
for x in range(n):
roll=int(input('Roll? '))
name=input('Name? ').upper()
theo=float(input('Theo? '))
stulist+=[[roll,name,theo]]
[Link](0)
[Link]()
[Link](stulist, fobj)
[Link]()
def readrecord():
fobj=open('[Link]', 'rb')
stulist=[Link](fobj)
[Link]()
for stu in stulist: print(stu[0],stu[1],stu[2])
def searchroll():
fobj=open('[Link]', 'rb')
stulist=[Link](fobj)
[Link]()
roll=int(input('Roll to Search? '))
for stu in stulist:
if roll==stu[0]:
print(f'Roll ={stu[0]}')
print(f'Name ={stu[1]}')
print(f'Theory={stu[2]}')
break
else: print(f'Roll={roll} Not Found!')
def searchname():
fobj=open('[Link]', 'rb')
stulist=[Link](fobj)
[Link]()
name=input('Name to Search? ').upper()
for stu in stulist:
if name==stu[1]:
print(f'Roll ={stu[0]}')
print(f'Name ={stu[1]}')
print(f'Theory={stu[2]}')
Page 15/18
Python Notes Class XII Binary File
break
else: print(f'Name={name} Not Found!')
def searchtheo():
fobj=open('[Link]', 'rb')
stulist=[Link](fobj)
[Link]()
found=0
for stu in stulist:
if stu[2]>=60:
print(stu[0],stu[1],stu[2])
found=1
if found==0: print('No Record Found!')
def editallrec():
fobj=open('[Link]', 'rb+')
stulist=[Link](fobj)
for stu in stulist:
stu[2]+=2
[Link](0)
[Link]()
[Link](stulist, fobj)
[Link]()
print('All Records Updated')
def editonerec():
fobj=open('[Link]', 'rb+')
stulist=[Link](fobj)
roll=int(input('Roll to Edit? '))
for stu in stulist:
if roll==stu[0]:
stu[2]+=2
print('Record Updated')
break
else:
print(f'Roll={roll} Not Found!')
[Link]()
return
[Link](0)
[Link]()
[Link](stulist, fobj)
[Link]()
def deleterec():
fobj=open('[Link]', 'rb+')
stulist=[Link](fobj)
roll=int(input('Roll to Delete? '))
for stu in stulist:
if roll==stu[0]:
[Link](stu)
print('Record Deleted')
break
else:
print(f'Roll={roll} Not Found!')
Page 16/18
Python Notes Class XII Binary File
[Link]()
return
[Link](0)
[Link]()
[Link](stulist, fobj)
[Link]()
while True:
print('---- Main Menu ----')
print('1. Add Records')
print('2. Display Records')
print('3. Search Records')
print('4. Update Records')
print('5. Delete Record')
print('0. Exit')
ch=input('Choice[0-5]? ')
if ch=='1': addrecord()
elif ch=='2': readrecord()
elif ch=='3':
while True:
print('---- Search Menu ----')
print('1. Search Roll')
print('2. Search Name')
print('3. Search Theo')
print('0. Return to Main')
ch2=input('Choice[0-3]? ')
if ch2=='1': searchroll()
elif ch2=='2': searchname()
elif ch2=='3': searchtheo()
elif ch2=='0': break
elif ch=='4':
while True:
print('---- Update Menu ----')
print('1. Edit All')
print('2. Edit By Roll')
print('0. Return to Main')
ch2=input('Choice[0-2]? ')
if ch2=='1': editallrec()
elif ch2=='2': editonerec()
elif ch2=='0': break
elif ch=='5': deleterec()
elif ch=='0': break
import pickle
fobj=open('[Link]','rb')
[Link](122)
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
[Link](120,1)
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
[Link](182,1)
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
[Link](-180,2)
emp=[Link](fobj)
print(emp[0],emp[1],emp[2],sep='\t')
Page 18/18