0% found this document useful (0 votes)
7 views55 pages

Python Files

The document provides an overview of file handling in Python, explaining the importance of files for permanent data storage and the types of backing storage available. It details the basic operations for file handling, including opening, writing, reading, and closing files, along with examples of how to implement these operations in Python. Additionally, it discusses file object attributes and provides a sample program to create a text file.

Uploaded by

skangralkar
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)
7 views55 pages

Python Files

The document provides an overview of file handling in Python, explaining the importance of files for permanent data storage and the types of backing storage available. It details the basic operations for file handling, including opening, writing, reading, and closing files, along with examples of how to implement these operations in Python. Additionally, it discusses file object attributes and provides a sample program to create a text file.

Uploaded by

skangralkar
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

Python Notes Class XII Text File

File: is either data or program stored in a backing storage permanently.

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.

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, Portable Solid State Drive, USB Flash Drive and SD Card
3. Optical Storage: CD, DVD and Blu-Ray Disc

A file can be stored in the backing storage as:


 Text file or CSV file – file stored in the backing storage in human readable format. Text file can be
read and edited using 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) or object(s) located in the RAM (main storage)
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) or
object(s) located in the RAM (main storage)

Three basic steps when working with file in Python:


 Open a file
 Write into a file OR, Read from a file
 Close file

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


 Using built-in independent function open()
Syntax: fileobject=open(filename, mode)
Function open() will create a file object and allocate a part of the RAM for the temporary
storage of the data before being transferred to the file located in the backing storage
fileobject is a Python object (variable) which is created with open()
filename name of the file located in the backing storage
file name is a string and generally file name has an extension
mode write ('w') mode / append ('a') mode / read ('r') / read-write mode ('w+'
/ 'a+' / 'r+'). If mode is missing, the default mode is the read mode
Example #1:
fobj=open('[Link]', 'w')
fobj is the file object
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
Example #2:
fobj=open('[Link]', 'a')
fobj is the file object
'[Link]' is the file name
'a' is the mode, 'a' stands for append mode
Difference between write mode and append mode will be discussed later.
FAIPS, DPS Kuwait Page 1 / 16 ©Bikram Ally
Python Notes Class XII Text File
Example #3:
fobj=open('[Link]', 'r') #OR, fobj=open('[Link]')
Default mode is read mode.
fobj is the file object (fr – file read)
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode

 Using keyword with and built-in independent function open()


Syntax: with open(filename, mode) as fileobject:
with is the keyword
Function open() will create a file object and allocate a part of the RAM for the temporary
storage of the data before being transferred to the file located in the backing storage
filename name of the file located in the backing storage
fileobject is a Python object which is created with open()
mode write mode / append mode / read mode / read-write mode

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

FAIPS, DPS Kuwait Page 2 / 16 ©Bikram Ally


Python Notes Class XII Text File
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
s1, s2 are the string variables (objects)
Example #2:
fobj=open('[Link]', 'w')
co,na,bs=1130,'KRISHNA',95700.0
rec=f'{co},{na},{bs}\n'
[Link](rec) #writes content of s1 into [Link]
[Link]()
fobj is the file object
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
rec is the string variable (object)

 Using file object method writelines()


Syntax: [Link](iterableobj)
File object method writelines() will transfer an iterable object (iterableobj) containing
strings into a text file. An iterable object can either be a single-line string, multi-line string,
list containing only strings, tuple containing only strings, dictionary where all keys are
strings. If an iterable like list or tuple or dictionary contains non-strings, writlines() will
trigger an error. Method writelines() returns None.
fileobject is a Python object which is created with open()
iterableobj is the data to be transferred into a file
Example:
fobj=open('[Link]', 'w')
s1='First Term Exam starts 23-May\n'
s2='''Last Exam is on 4-June
Result PTM on 15-June\n
Summer break begins from 16-June'''
s3={'ARUN':88, 'RITA':75, 'TARA':84, 'RAJA':82}
[Link](s1) #writes content of s1 into [Link]
[Link](s2) #writes content of s2 into [Link]
[Link](s3) #writes content of s3 into [Link]
[Link]()
fobj is the file object
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
s1,s2,s3 are the iterable objects (variable) containing strings
Example #2:
fobj=open('[Link]', 'w')
data1=['1130, ATUL JAIN, 95700.0\n',
'1132, GAURAV KUMAR,97600.0\n',
'1134, TEENA PAUL, 93500.0\n']
data2=('1136, SUNILA GARG, 94700.0\n',
'1138, NILESH GUPTA, 97500.0\n')
[Link](data1) #writes data1 into [Link]
[Link](data2) #writes data2 into [Link]
[Link]()
fobj is the file object
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode
data1, data2 are the iterable objects (variable) containing strings

FAIPS, DPS Kuwait Page 3 / 16 ©Bikram Ally


Python Notes Class XII Text File
How to read from a text file? In Python data can be read from a text file in four ways:
 Using file object method read()
Syntax: strobj=[Link]()
Method read() will transfer content of an entire text file as a string into a string object
(variable). Return value of read() method is string.
fileobject is a Python object which is created with open()
strobj is the string variable/object to store the entire text file as a string
Example #1:
fobj=open('[Link]', 'r')
data=[Link]() #text file is stored as a string in data
fobj is the file object
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable (object)
Example #2:
fobj=open('[Link]', 'r') First 100 characters of the text
data=[Link](100)
file is stored as a string in data.
fobj is the file object
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode
data is the string variable (object)

 Using file object method readline()


Syntax: strobj=[Link]()
Method readline() will transfer a line of text (till a new line character is encountered or
reads the entire file when there is no new line character present in the file) from a text file
to a string object(variable). Return value of readline() method is string.
fileobject is a Python object which is created with open()
strobj is the string variable/object storing a line of text (string) read from a text file
Example #1: Reads a line of text (string) from a text file
fobj=open('[Link]', 'r')
till it encounters a '\n' or end of file.
data=[Link]()
fobj is the file object Without any '\n' in the text file, read() and
'[Link]' is the file name readline() will produce same result.
'r' is the mode, 'r' stands for read mode
data is the string variable (object)

 Using file object method readlines()


Syntax: strlist=[Link]()
Method readlines() will transfer entire data from a text file to a list of strings (strlist).
Method readline() returns a list (list of string(s).
fileobject is a Python object which is created with open()
strlist is the data (list of strings) to store an entire file, read from a text file, assuming
every line in the text file is terminated by '\n' and if there are no '\n' in the text file, then a
list will be created with a single string.
Example #1: Reads the entire text file as a list of
fobj=open('[Link]', 'r') strings, if every line in the text file is
data=[Link]() terminated by '\n'. Number of elements
fobj is the file object in the list depends on number of lines
present in the text file.
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode
data is the list of strings
FAIPS, DPS Kuwait Page 4 / 16 ©Bikram Ally
Python Notes Class XII Text File
 Using for loop and file object as an iterator
Syntax: for line in fileobject: #process / display every line
fileobject is a Python object which is created with open()
line will represent every line of text (string) read from the text file through the
fileobject assuming every line is terminated by '\n'.
Example #1:
fobj=open('[Link]', 'r')
for line in fobj: print([Link]())
fobj is the file object
'[Link]' is the file name
'r' is the mode, 'r' stands for read mode
line is a string (line of text read from the file)

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

Running of the scripts produces following outputs:


[Link] w False
[Link] a False
[Link] ab False
[Link] rb False
[Link] w True
[Link] r True
[Link] ab True
[Link] rb True

FAIPS, DPS Kuwait Page 5 / 16 ©Bikram Ally


Python Notes Class XII Text File
1. Write a Python program to create a text file '[Link]' by adding following lines in the file:
Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
s1='Costo with its first store in Khaitan has\n'
s2='positioned itself as a cost-effective\n'
s3='shopping destination. Costo is all set\n'
s4='to open its second outlet in Fahaheel.\n'
fw=open('[Link]', 'w')
[Link](s1)
[Link](s2)
[Link](s3)
[Link](s4)
[Link]()
OR,
lines='''Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.\n'''
fw=open('[Link]', 'w')
[Link](lines)
[Link]()

 Open file using keyword with


s1='Costo with its first store in Khaitan has\n'
s2='positioned itself as a cost-effective\n'
s3='shopping destination. Costo is all set\n'
s4='to open its second outlet in Fahaheel.\n'
with open('[Link]', 'w') as fw:
[Link](s1); [Link](s2)
[Link](s3); [Link](s4)
Opening a file using keyword with, will automatically close the file without [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

FAIPS, DPS Kuwait Page 6 / 16 ©Bikram Ally


Python Notes Class XII Text File
To add more data to an existing file, without data loss, a file must be open in append mode. Edited
program is given below by opening the file in append mode ('a').
Write Mode Append Mode
 If a file does not exist, a new file is created  If a file does not exist, a new file is created
 If a file exists, new data overwrites the existing  If a file exists, new data will be written at the
data in the file => loss of data end of the file => no loss of data

#Edited program is given below:


fa=open('[Link]', 'a')
s1=' Costo is part of Regency Group which is among\n'
s2=' the foremost retail players in GCC region.\n’
[Link](s1)
[Link](s2)
[Link]()

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

Running of the program produces following output:


Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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

FAIPS, DPS Kuwait Page 7 / 16 ©Bikram Ally


Python Notes Class XII Text File
Running of the program produces following output:
Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
Costo is part of Regency

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

Running of the program produces following output:


Costo with its first store in Khaitan has

positioned itself as a cost-effective

shopping destination. Costo is all set

to open its second outlet in Fahaheel.

Costo is part of Regency Group which

is among the foremost retail players

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

Running of the Python program produces following output:


Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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

Running of the Python program produces following output:


Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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

Running of the Python program produces following output:


Costo with its first store in Khaitan has
positioned itself as a cost-effective
shopping destination. Costo is all set
to open its second outlet in Fahaheel.
Costo is part of Regency Group which
is among the foremost retail players
in GCC region.

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

Running either of the Python program will produce following output:


Costo with its first store in Khaitan has positioned itself as a
cost-effective shopping destination. Costo is all set to open its
second outlet in Fahaheel. Costo is part of Regency Group which is
among the foremost retail players in GCC region.

In both the cases, data will be stored as a single string.


FAIPS, DPS Kuwait Page 9 / 16 ©Bikram Ally
Python Notes Class XII Text File
fr=open('[Link]', 'r')
data=[Link]() #data is a list with a single string
print(data)
[Link]()

Running of the Python program produces following output:


['Costo with its first store in Khaitan has positioned itself as a
cost-effective shopping destination. Costo is all set to open its
second outlet in Fahaheel. Costo is part of Regency Group which is
among the foremost retail players in GCC region.']

fr=open('[Link]', 'r')
data1=[Link]() #First [Link]()
data2=[Link]() #Second [Link]()
print(data1)
print(date2)
[Link]()

Running Python program will produce following output:


Costo with its first store in Khaitan has positioned itself as a
cost-effective shopping destination. Costo is all set to open its
second outlet in Fahaheel. Costo is part of Regency Group which is
among the foremost retail players in GCC region.

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.

9. Write a Python menu driven program to do the following:


 Append the following files in an existing text file '[Link]':
COSTO is a customer driven purchase
store where customer feedbacks determine
the future products in the store.
 Read and display the text file '[Link]' and at the end display number of lines present in the file.
 Read and display the text file '[Link]' and at the end display number of words present in the file.
 Read and display the text file '[Link]' and at the end display number of characters present in the
file.
 Read and display the text file '[Link]' and at the end display number of uppercase characters,
lowercase and number of digits present in the file.
 Read and display the text file '[Link]' and at the end display number of special characters and
number of white space characters present in the file
 Exit from the Menu

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

FAIPS, DPS Kuwait Page 16 / 16 ©Bikram Ally


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('[Link]', 'w', newline="")
fw is the file object (fw – file write)
'[Link]' is the file name
'w' is the mode, 'w' stands for write mode

Example #2: fa=open('[Link]', 'a', newline="")


fa is the file object (fa – file append)
'[Link]' 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('[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]()

Example #2: fr=open('[Link]', 'r')


#Open file for read operation
[Link]()
fr is the file object (fr – file read)
'[Link]' 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('[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:

import csv In the CSV file, default separator


def append(): comma (,) will be replaced by
fobj=open('[Link]', 'w', newline="") tilde (~). Now CSV file will be
cwobj=[Link](fobj) created without any blank line
#OR, cwobj=[Link](fobj, delimiter='~')
after every record / row.
n=int(input('Number of Records? '))
for x in range(n): Content of the file CSV file '[Link]'
roll=int(input('Roll? ')) will be overwritten by new set of inputs since
name=input('Name? ').upper() the CSV file '[Link]' already exits.
marks=float(input('Marks? '))
stu=[roll, name, marks] #stu=(roll, name, marks)
[Link](stu)
[Link]() Call to method [Link](stu) is inside the for-loop.
OR,
def append():
with open('[Link]', 'w', newline="") as fobj:
cwobj=[Link](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)
[Link](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('[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)

Function to display a CSV file is given below:


import csv
def display():
fobj=open('[Link]') #OR, fobj=open('[Link]', 'r')
stulist=[Link](fobj)
#OR, stulist=[Link](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 (,).
[Link]()
OR,
def display():
with open('[Link]') as fobj:
#with open('[Link]', 'r') as fobj: Read ('r') mode is the default
stulist=[Link](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 [Link](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('[Link]')
stulist=[Link](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
[Link]()
if found==0: print(roll,'not found in the file')
OR,
def searchroll():
with open('[Link]') as fobj:
stulist=[Link](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('[Link]')
stulist=[Link](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')
[Link]()
OR,
def searchroll():
with open('[Link]') as fobj:
stulist=[Link](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('[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 search for marks<33 is given below:


import csv
def searchmarks():
fobj=open('[Link]')
stulist=[Link](fobj)
found=0
for stu in stulist:
if float(stu[2])<33.0:
print(stu[0], stu[1], stu[2])
found=1
[Link]()
if not found: print('No such records found!')
OR,
def searchmarks():
fobj=open('[Link]')
stulist=[Link](fobj)
c=0
for stu in stulist:
if float(stu[2])<33.0:
print(stu[0], stu[1], stu[2])
c+=1
[Link]()
print('Number of Records=',c)

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 search for marks>=40 and marks<=60 is given below:


import csv
def searchmarks():
fobj=open('[Link]')
stulist=[Link](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
[Link]()
if found==0: print('No such records found!')
Page 9/15
Python Notes Class XII CSV File
OR,
import csv
def searchmarks():
fobj=open('[Link]')
stulist=[Link](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
[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 every student using a nested list.


import csv
def editrecords():
fobj=open('[Link]')
stulist=list([Link](fobj))
for stu in stulist:
stu[2]=float(stu[2])+2
[Link]()
fobj=open('[Link]', 'w', newline='')
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
print('All Records Updated in the File')
OR,
Page 12/15
Python Notes Class XII CSV File
import csv
def editrecords():
fobj=open('[Link]', 'r+', newline='')
stulist=list([Link](fobj))
for stu in stulist: stu[2]=float(stu[2])+2
[Link](0)
[Link]()
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
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('[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')

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


import csv
def delrecord():
fobj=open('[Link]')
stulist=[Link](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]:
[Link](stu)
#[Link]([Link](stu))
Page 14/15
Python Notes Class XII CSV File
#del stulist[[Link](stu)]
found=True
break
[Link]()
fobj=open('[Link]', 'w', newline='')
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
if found:
print('Record Deleted From the File')
else:
print(roll,'Not Found in the File')
OR,
import csv
def delrecord():
fobj=open('[Link]', 'r+', newline='')
stulist=[Link](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]:
[Link](stu)
#[Link]([Link](stu))
#del stulist[[Link](stu)]
found=True
break
[Link](0)
[Link]()
cwobj=[Link](fobj)
[Link](stulist)
#for rec in stulist: [Link](rec)
[Link]()
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
If the file does not exist, a new file is created
('a') 
 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
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.

Some common runtime errors are discussed below:


 Syntax Error, Name Error and Type Error
x=100
y=input('Value / Expression / Variable Name? ')
s=x+eval(y)
print(s)

Running of the script


Value / Expression / Variable Name? 200
300
Variable x is 100 and eval(y) is 200 and hence s is 300.

Running of the script


Value / Expression / Variable Name? 10+20+30
160
Variable x is 100 and eval(y) is 30(10+20+30) and hence s is 160.

Running of the script


Value / Expression / Variable Name? x
200
Variable x is 100 and eval(y) is x (x is a valid variable name and x is defined) and hence s is
200 (x+x is 200).

Running of the script


Value / Expression / Variable Name? 3z
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
File "<string>", line 1
3z
^
SyntaxError: unexpected EOF while parsing
Variable x is 100 but eval(y) is 3z. According to Python 3z is not a correct variable name. Hence
a runtime error.

Running of the script


Value / Expression / Variable Name? z3
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
File "<string>", line 1, in <module>
NameError: name 'z3' is not defined

FAIPS, DPS Kuwait Page 1 of 6 ©Bikram Ally


Python Notes Class XII Exception
Variable x is 100 but eval(y) is z3. z3 is a valid variable name but Python is unable to identify
z3 because z3 is not defined. Hence the runtime error.

Running of the script


Value / Expression / Variable Name? y
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
s=x+eval(y)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Variable x is 100 but eval(y) is y. y is a valid variable name and defined but x and y cannot be
added because x is int and y is str. Hence the run-time error.

 Zero Division Error


x=100
y=input('Value / Expression / Variable Name? ')
z=x/eval(y)
print(z)

Running of the script


Value / Expression / Variable Name? 25
4.0
Variable x is 100 and eval(y) is 25 and hence z is 4.0. So long the inputted value/expression is
non-zero, expression x/eval(y) will give correct result.

Running of the script


Value / Expression / Variable Name? 12+8
5.0
Variable x is 100 and eval(y) is 20 (12+8) and hence z is 5.0.

Running of the script


Value / Expression / Variable Name? 0
Traceback (most recent call last):
File "D:\Python\[Link]", line 3, in <module>
z=x/eval(y)
ZeroDivisionError: division by zero
Variable x is 100 and eval(y) is 0. When using operators /, // and %, if the second operand is
zero, it will trigger a runtime error.

 Value Error
import math
x=eval(input('Value / Expression / Variable Name? '))
y=[Link](x)
print(y)

Running of the script


Value / Expression / Variable Name? 25
5.0
eval(x) is 25, square root of 25 is 5.0 and hence y is 5.0. So long the inputted value/expression
is non-negative, [Link](x) will give correct result.

Running of the script


Value / Expression / Variable Name? -25
Traceback (most recent call last):
FAIPS, DPS Kuwait Page 2 of 6 ©Bikram Ally
Python Notes Class XII Exception
File "D:\Python\[Link]", line 3, in <module>
y=[Link](x)
ValueError: math domain error
eval(x) is -25, [Link]() cannot calculate square root of -25 and hence run-time error.

 Index Error
alist=[23,67,45,74]
print(alist[5])

Running of the script


Traceback (most recent call last):
File "D:\Python\[Link]", line 2, in <module>
print(alist[5])
IndexError: list index out of range
When accessing an element of a list (tuple), correct index of an element in a list (tuple) is 0 to length
of (lust/tuple) – 1. List alist has 4 elements, index varies from 0 to 3. Hence index 5 is out of range.

 File Not Found Error


df=open('[Link]')
data=[Link]()
[Link]()
print([Link]())

Running of the script


Traceback (most recent call last):
File "D:\Code\Python\[Link]", line 1, in <module>
tf=open('[Link]')
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'
Opening a file '[Link]' in read mode when the file does not exist, will trigger a run-time error.

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)

FAIPS, DPS Kuwait Page 3 of 6 ©Bikram Ally


Python Notes Class XII Exception
except:
print('Error')
print('The end')

Running of the script


Number? 0
Error
The end
Inputted value of x is '0' and eval(x) is 0. Statement after the try triggers
ZeroDivisionError exception and control jumps to except clause and the statement after except
clause is executed.

Running of the script


Number? 25
4.0
The end
When statement after the try does not trigger any exception, dividing 100 by 25 that is 4.0 is
displayed and also The end is displayed too.

Modified Python script is given below with else clause included.


x=input('Number? ')
try:
y=100/eval(x)
print(y)
except:
print('Error')
else:
print('Quotient=',y)

Running of the script


Number? 25
Quotient= 4.0
Statement after the try does not trigger any exception. Control jumps to the else clause and statement
after the else clause is executed. except clause will handle all exceptions triggered by the statement
after try.

Running of the script


Number? z
Error
Inputted value of x in 'z' and eval(x) is z. Variable z is not defined. Statement after the try
triggers NameError exception and control jumps to the except clause.

Running of the script


Number? 10z
Error
Inputted value of x in '10z' and eval(x) is 10z. 10z is neither an expression nor a variable not
defined. Statement after the try triggers SyntaxError exception and control jumps to the except
clause.

Running of the script


Number? x
Error

FAIPS, DPS Kuwait Page 4 of 6 ©Bikram Ally


Python Notes Class XII Exception
Inputted value of x in 'x' and eval(x) is x. x is a string variable (str type). Statement after the try
triggers TypeError exception and control jumps to the except clause.

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

Running of the script


Number? 20
Quotient= 5.0
End of script
The statement after the try does not trigger any exception. Control jumps to the else clause and the
statement after the else clause is executed. finally clause always gets executed.

Running of the script


Number? 0
Error
End of script
Inputted value of x in '0' and eval(x) is 0. Statement after the try triggers
ZeroDivisionError exception and control jumps to the except clause and the statement after the
except clause is executed. finally clause always gets executed. If the predefined Python exceptions
are to handled separately, then we have to use second syntax of try-exception.

 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:

x=input('1st Number? ')


y=input('2nd Number? ')
z='ZERO'
try:
q=eval(x)/eval(y)
except SyntaxError:
print('Incorrect variable name')

FAIPS, DPS Kuwait Page 5 of 6 ©Bikram Ally


Python Notes Class XII Exception
except NameError:
print('Variable not defined')
except TypeError:
print("Cannot divide 'int' and 'str'")
except ZeroDivisionError:
print('Division by zero')
else:
print('Quotient=',q)
finally:
print('End of script')

Running of the script


1st Number? 100
2nd Number? 25
Quotient= 4.0
End of script

Running of the script


1st Number? 100
2nd Number? 30a
Incorrect variable name
End of script

Running of the script


1st Number? 100
2nd Number? deno
Variable not defined
End of script

Running of the script


1st Number? 100
2nd Number? z
Cannot divide 'int' and 'str'
End of script

Running of the script


1st Number? 100
2nd Number? 0
Division by zero
End of script

FAIPS, DPS Kuwait Page 6 of 6 ©Bikram Ally


Python Notes Class XII Binary File
Python pickle
Pickle is used for serializing and de-serializing Python object. Serialization refers to the process of
converting an object in memory to a byte stream that can be stored on disk (backing storage). Later on,
this byte stream can then be retrieved and de-serialized back to a Python object (variable). In Python
process of serialization and de-serialization is called is pickling. For pickling in Python has pickle module.

Important functions for binary file handling:


 fobj=open('[Link]','wb') #with open('[Link]','wb') as fobj:
Built-in function open() creates a file object. Generally, a binary data has extension .DAT, but a
binary data file can have any other extension. When opening a binary data file, the mode parameter
has an extra letter 'b' to indicate that the data file [Link] is a binary data file.
 [Link](data, fobj) – function from pickle module and it writes values stored in the
variable data, into a binary data file using file object fobj. Variable data represents data either as
a list(tuple) or as a dictionary. In fact function dump() transfers data to the buffer.
 data=[Link](fobj) – is function from pickle module and it reads data from a binary
data file using file object fobj, into a variable (object) data. Variable data can either be a
list(tuple) or dictionary type depending how the data was dumped. If the binary file was created using
a list(tuple), then [Link](fobj) will read a list(tuple) and store the data in the variable
data. Binary data file containing tuple type data If the binary file was created using a dictionary,
then [Link](fobj) will read a dictionary and store the data in the variable data.
 [Link]() – will close a binary data file using the file object fobj.

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

File Pointer and Binary File


Now with binary file we will see the use of seek(pos, whence). Binary data file '[Link]'
contains records as [CODE, NAME, BSAL, HRA, GSAL].
Content of [Link] with the position of file pointer after end every record:
2001 GUATAM SHARMA 155000.0 31000.0 186000.0 62
2002 DEEPIKA RAO 166000.0 33200.0 199200.0 122
2003 JATHIN KUMAR 155000.0 31000.0 186000.0 183
2004 ADITI GUPTA 150000.0 30000.0 180000.0 243
2005 ASEEM KAPUR 170000.0 34000.0 204000.0 303
2006 TINA DASH 155000.0 31000.0 186000.0 361
2007 KUNAL THAKUR 155000.0 31000.0 186000.0 422
Page 17/18
Python Notes Class XII Binary File
2008 DILIP SHAW 155000.0 31000.0 186000.0 481
2009 JYOTHI SURESH 185000.0 37000.0 222000.0 543
2010 MITALI JHA 160000.0 32000.0 192000.0 602

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

Running of the program produces following output:


2003 JATHIN KUMAR 155000.0 31000.0 186000.0
2006 TINA DASH 155000.0 31000.0 186000.0
2010 MITALI JHA 160000.0 32000.0 192000.0
2008 DILIP SHAW 155000.0 31000.0 186000.0

Explanation of the output:


[Link](122) moves the file pointer from the beginning of the file, to the end of
second record and the beginning of the third record
emp=[Link](fobj) reads the third record from the file
print(emp) displays third record
[Link](120,1) moves the file pointer 120 bytes forward from the current location
(183 bytes), to the end of 5th record and the beginning of the 6th record
emp=[Link](fobj) reads the sixth record from the file
print(emp) displays sixth record
[Link](182,1) moves the file pointer 182 bytes forward from the current location
(361 bytes), to the end of ninth record and the beginning of the tenth
record
emp=[Link](fobj) reads the tenth record from the file
print(emp) displays tenth record
[Link](-180,2) moves the file pointer 180 bytes backward from the end of the file to
the end of seventh record and the beginning of the eight record
emp=[Link](fobj) reads the eight record from the file
print(emp) displays eight record

Page 18/18

You might also like