Updating in a Binary File
Developed By:- Vishant D Khobragade
PGT CS
K V VSN NAGPUR
What is Updating?
➢Updating mean modification in existing
value(s).
➢There are three steps for updating in the file:
• Locate the records to be updated
• Make changes in values where you want.
• Write back onto the file.
Accessing & Manipulation in a File
➢ Python provides two function which helps us to
manipulate the value(s) in the file. For
manipulating, you have to transfer file pointer at
the desired location.
➢ Two functions are: (1) tell() & (2) seek()
➢ The tell() function returns the current position of
file pointer in the file.
Syntax:- <file-object>.tell()
It returns integer type value. It means it tells on
which byte file pointer lie on.
Example
f1=open(“[Link]”)
print([Link](), “:-It represent the initial position”)
print([Link](5))
print([Link](),”:-Cursor on 5th byte”)
Note:-File position begins with zero byte.
The seek() function
➢ The seek() function is used to transfer file pointer at
the desired location or specified position in the file.
Syntax:- <file-object>.seek(offset[,mode])
where offset is specifying number of bytes
mode is a number either 0 or 1 or 2
0 specifies beginning of the file
1 specifies the current position of the file
pointer.
2 specifies end of the file.
➢ Note:- Here, mode is optional. If it is not mentioned
then default value of mode is 0.
Example
➢ Look at the following examples: Consider the previous file is
opened. i.e. f1=open(“[Link])
1. [Link](20) :- It will transfer the file pointer at 20th byte from the
beginning.
2. [Link](20,0) :- It will transfer the file pointer at 20th byte from the
beginning.
3. [Link](20,1) :- It will transfer the file pointer forward at 20th byte
from the current position of the file pointer.
4. [Link](-20,2) :- It will transfer the file pointer backward at 20th
byte from the end of the file.
5. [Link](-20,1) :- It will transfer the file pointer backward at 20th
byte from the current position of the file pointer.
Note:-
✓ Backward movement of the file pointer is not possible from the
beginning of the file.
✓ Forward movement of the file pointer is not possible from the end
of the file.
Example
# Following program used to find the total number of
bytes in a program
f1=open(“[Link]”)
str1=[Link]()
print(“Total number of bytes:”,[Link]())
# Following program shows the movement of file pointer
in a program from end of the file & display last 10
characters of the file.
f1=open(“[Link]”)
[Link](-10,2)
str1=[Link](10)
print(“Last 10 byte is:”,str1)
ASSIGNMENT
1. Consider the binary file [Link] which is created
earlier. Write a program to update the records of
the file [Link] so that those who have scored
more that 90.0 and less than 95.0, get additional
bonus marks of 2.
2. Write a program to modify the name of student
whose roll number is 111 as “Himanshu”.