oF Computer sconce wan Python
me Program shown above uses while loop under try block. The moment system encounteg,
the fle ithe BY clause traps the error and passes the control to the except Block to cian"
the file. Hence, the error message will not be displayed on the user's screen.
Appending a Binary File
Tl now, we have discussed the writing and reading modes in a binary file. The write moj,
allows writing data into the file whereas the read mode allows retrieving data from the file,
Suppose, you want to add few more data items (records) in the existing file. What will you
do? If you open an existing file in write mode ("wh"), then new records will overwrite the
existing data. In order to add new record at the last position, Python has provided another
mode known as Append Mae,
Hence, appending a file is referred to as adding few records in an existing file. When an
existing file is opened in append mode, the file pointer is set at the last record. When 4
new entry is made, it is written into the file after the last record. This is the reason that the
existing records are not affected while adding new records. In case, a file opened in append
mode does not exist, it will be created to store the records from beginning.
Following steps are to be noted while appending a file.
* Define a file object which serves as a link to the existing file.
* Open the existing file in append mode ("ab").
+ Set the path to file (optional).
For example:
The file ‘Name.dat' is already created using a list with the sub-lists containing name and
class of three students as shown below:
Name: Akash Goyal
Class: XI B
Name: Payal Raj
Class: XT A
Name: Ankita Agarwal
Class: XT C
Now, you want to add few more records in the existing file. To do so, open the
file in append mode and perform the task as shown below:
# A Python code to add more records to a binary file
import pickle
fwb= open("Name.dat’,"ab”
record=[ ]
che"
while ch=="Y'or ch:
name=input("Enter Name:")
cs=input("Enter Class:")
data=[name,cs]
record.append (data)
ch=input("Do you want to add more records...? Enter(Y/N)
pickle.dump(record,fwb)
fwh.close( )
print("File is saved.")|
Chapter a Fin anc ED
records are added as shown belay
nee”
RESTART: C:\Users\Dilip Kumar Do
cae oe
ror Name: Payal Verma Y\Desktop\Writellin py===e=====
pot :
goer Class NTT A
poyou wane add more records..2 Enter(¥/Njy
ver Name: Jaya Chauhan
fi
1 Class: XIU B
x want to add more records..? Enter(¥/N):n
Fatt
Do you
file is saved:
>
ren the file in read mode to retrieve and display all the records by using the following
conte snippet:
sArython code to display the updated records from the binary file
import pickle
frb= open("Name.dat","rb")
‘Updated records of the file Name.dat:")
while True:
rec=pickle.load(rb)
for a in rec:
print(a)
except:
frb.close( )
print(’Program Ends!")
Updated records of the file Name.dat:
Python 38:1 Shall ao
Eat Stell Debug Options Window Help
T (tags/v3.6.1:15293b6, Geo 18 2019, 22ST) [WSC ViIBI6 32 bit Catel]
ving
help", "copyright", "credits" or "License()" for more information.
= RESTART: Ci\Users\DLLip Kumar Dey\Desktop\prog.Py ~
KET Ch)
var a)
OE BF)
The output ‘window shown above illustrates that the existing file is updated after appending,
two new records,
Searching Records
tis a technique to find a record in an existing file. It is performed with the help of a flag
‘type of variable) that is set to one (1) of reset to 2e70 (0) to ensure whether a particular
is present or not in the file respectively.ED ext000k of Computer Scionce with Python
Refer the previous file ‘Admission.dat’ (in Exception Handling) which contai
admission number of some students. Now, a record with specific name is to be searched in
the file. Perform the following steps to carry out this task:
(i) Open the file in read mode.
(ii) Set fag = 0.
(ii) Retrieve a record from the file.
(iv) Compare the name to be searched with the name in the record.
(v) If name is found then set flag = 1 and exit the iteration else repeat through step (iii)
unless end of the file has encountered.
(vi) If flag = 1 then display "Record is found” else display "Record is not found”.
(vii) Close the file.
the name and
With reference to the previous file ‘Admission.dat’ containing name and admission number
of the students using different lists. A record is to be searched based on the name of a
student entered from the keyboard. If it is found, it will display ‘Record Found’, otherwise
it will display ‘No such record present !!, The program is as illustrated below:
# A Python code to search a record from the binary file
import pickle
frb= open("Admission.dat","rb")
found=0
nm=input("Enter name to be searched:")
try:
while True:
rec=pickle.load{frb)
if(rec{0]==nm):
print("Record Foun
print(rec)
found=1
break
print("No such record present!:")
frb.close( )
print("Program Ends!")
Output of the code after searching a record from pre-existing file:
Free "herp, sconyriant*, “erediter or “iicensa()* for more Anformatton,
Jae ———————— nasrants c1/usere/Di1ip Kumar Dey/Desktop/Test.
Enter vane to be seacchediRunel Seinmah nn w?/Deehtop/Testpy
fRecora' Fosnait
{Srinan‘Satowan’, 19V31/028/20"1
[eme——nvm——vom= RESTART: C1 /U20r9/D11ip Kumar Dey/Deaktop/Test.py nemeanewnnene
fencer name to be searchedsAkaah Mittal’ aedrandom Accessing In binary files Chapter = Fla Hancirg ED
evi ‘hapter,
in the previous chapter, you learnt about
fie cursor. The file pointer i he file point
oF et has to be eles oo 10 point a eestor late Ge Sree
jons are used viz, sec as to be modified. rom where a specific
functi () and tell( ), . To manage the file pointer, two
The seek( ) function
ce sek() function is used to change the posit ql
the file pointer at a specific position in ie pene Becioiineh aang be
syntax fpseek(off-set, from-w!
= i what)
ee Retorence point
the fle pointer
mes reference poet rama al osiion refering to which the file pointer is displaced
foe nd 2) as explained below It is mentioned with three different options
0 : It refers the beginning position of the file.
1 : Jt refer the current position of the file pointer.
2 : It refers the end position of the file.
‘The off-set argument of the seek( ) function has the following features:
« Itcan be negative or positive.
« A positive value moves file pointer ahead in the file.
« Anegative value moves file pointer back in the file.
Note g - -
«+ The beginning (0) is the default reference point. \
+ The reference points (current and end) are only used while working with binary fle.
uses beginning (0) as the reference point.
«+ The forward movement of the file pointer is
+ The backward movement of the file pointer
|
‘The text file advays |
not possible from end position of the file. \
is not possible from beginning position of the file. |
The table shown below illustrates the shifting of the file pointer using seok( ) function:
ee TT ETE THe
Description im eT
ahead from the beginning of the file.
/ Tt will shift the fi pytes ahead
Tt will also shift the file pointer 7 bytes ahead from beginning of the file.
“Fe will shift the file pointer 5 bytes ahead from current position of the file
Seem |
pointer." — —
"Tt will shift the file pointer 12 bytes: back from end of the file :
The tell( ) functi
hacen ‘on of the file pointer in the file.
The tell( ) function returns the current positi
Syntax: .tell( )
For example:
fp-tell( ): It will return the current
A file "Stdat" is created to store 4 §
Hello! learning,
¢ position of the file pointer
entence as:
python file is a tunED extL00¥ of Computer Scionco with Python
A program to understand the applications of serk( ) and fell() functions to manage random
accessing from the file is illustrated below:
# A program to illustrate seek( ) and tell( ) functions in a binary file
fib= open("Stdat',"1b")
Print("Content from the file:\n",fwb.read( )) .
fwh.seek(6) # File pointer shifted 6 bytes ahead from beginning,
print("Content from the file:\n",fwb.read( ))
print(‘Current location of file pointer:\t",fwb.tell( ))
fwhseek(6) # File pointer shifted 6 bytes ahead from beginning
print(‘Content from the file:\n" fwb.read(9)) # Reads 9 bytes from 6th position
print("Current location of file pointer:\t",fwb.tell( ))
fvb.seek(7, 1) # File pointer shifted 7 bytes ahead from current position of the file pointer
print(‘Content from the file:\n",fwb.read( ))
print(‘Current location of file pointer:\t",fwb.tell( ))
fwbseek(-8,2) __# File pointer shifted 8 bytes back from the end position
print("Content from the file:\n",fwb.read(9))
print("Current location of file pointer:\t",fwb.tell( ))
Output of the code:
ile ta" font
"S fone
Jccctent location of £110 potntert
lot
Implementation of wb+, rb+ and ab+ modes in binary files
We have already learnt the use of ‘wb’, 'rb' and ‘ab’ modes of operations in the binary file.
‘The binary file also uses some more modes of operations such as ‘wb+, 'th+ and ‘ab+".
Let us discuss their applications.
Use of ‘wb+! (write and read) in a binary file
The 'wb+' mode enables a binary file to be opened in write as well as read mode. It means,
after writing the contents in the file, you need not re-open it in read mode for accessing
the records. When writing into the file is over, you must use seek(0) function to bring the
file pointer at the beginning of the file. Further, reading operation can be done similar to
the read mode (rb). To understand the concept, a program is illustrated below:
# A program to write and read data using ‘wb+' mode in a binary file
import pickle
f= open(’Phone.dat',"wb+")
rec=['Samsung Galaxy’,Redmi Note 6'/Oppo K4''Realme XT']y
|
sledump(rec) Chapter 6 Fla Hansing DP
pain records are:")
fscok)
| fecepickledoad()
print)
gelose()
of the code:
utp
Dis, ITD
weeditet or “Ltcen
7 for move information.
Sere)
Use of 'rb+' (read and write) in a binary file
ahs mie lin a file in read as well as write mode. In this situation, the order
(first reac’ af | write) must be followed strictly. A program to work with a file "Sports.
{at" in ‘rb+’ mode is illustrated below: ame ;
+ Aprogram to read and write data using rb’ mode in a binary
g ‘rb+" mode
aio ina binary file
f= open("Sports.dat’,"rb+")
print("Reading of records of the file:") Note
recl=pickleload(f) 1 in ‘be mode, it you try to
pritee}) write some content before \
Fae[ Long Jump’, ‘High Jump, ‘Disc Throw’) wae oreo ne
pickle.dump(rec2, f) existing content.
fclose( )
print("Writing of records done!")
Output of the code:
Python
(intel) } on win32
lrype *help", “copysight™+
b>>
p>? pestants ¢1/020r9/Di14P
lneading of records of the file)
idai Rishore', ‘sonam Jain"
firiting of records done!
p> 1
vereaits” oF “iicense()" for nore informatis
umar Dey/Desktop/B2-PY —=—————
‘aman Kunar")
) in a binary file
ary file in append
Use of 'ab+' (append and read
and read mode. Before opening a file in
s in the hard disk. It works similar to ‘wb+"
isti will be erased when. records
mode. Whereas, in 'ab+ mode, the records are added into
ents. In case, a fle does not exist in the hard disk,
This mode is used to open a bin:
this mode, you must ensure thal
Mode, The only difference is
ar writen and opened in ‘wb+"
file rather erasing the previous
t the file existsI sy
QD tt004 oF computor donc win Python
iC will create a file to store records from the beg
iMustrated below:
# A program to write data using ‘ab! mode In a binary file
import pickle
£ = open(’Captain.dat’,"ab +") ’
reed=|'RC Bangalore’, ‘Chennal Super Kinge!, ‘Mumbai Indians']
pickledump(rec2, )
print(’Appending done!")
fseek(0)
reel =pickle.load({)
ree2=pickle.load(f)
print("Existing records’
int(recl)
prin('Appended records:
print(rec2)
f.close( )
dinning, A progam Using DY mag,
; i
Output of the code:
TR Python 3.81 She
Fle Edit Shell Debug Options Window Help
Python 3.8.1 (tags/v3-6.1:1b293b6, Dec 16 2019, 22139224) [MSC v.1916 32 Bit (Intel
Jon win32_
type "help", “copyright”, “credits” or “license()" for more information.
>>>
[Appending dono!
Existing records|
('Virat Kohli",
ndod records:
ee ‘Dengalore's "Chennai Super Kings", ‘Munbat Indians")
>>>
RESTART: Cs\Usora\Dilip Kumar Dey\Desktop\B2.py ===—====-=nmwm=
13 Dhoni*, ‘Rohit Sharma] |
maa eo
Updating a file
Updating a file is referred to as making changes in the records of an existing file. 7?
understand the updating process, let us take a problem for our discussion.
A file "Result.dat" is created to store roll number, name and marks in computer science!
some students in the form of sub-lists of a list. The name of a student is to be chang
whose roll number is entered from the keyboard.
‘The steps to perform the task are as given below:
(i) Open the file in read and write (rb+) mode.
(ii) Enter the roll number whose name is to be changed.
(ili) Set flag = 0
(iv) Retrieve the complete list (along with all the sub-lists) from the file.
(v) Get a sub-list from the list and repeat step 6 unless end of external list has encounter
(vi) Check whether given roll number is found or not, If yes,
then
change name in the sub-list
set flag = 1
terminate the iteration.