Random File Access in Python
seek() and tell() Functions
Python File seek() Method
syntax:
fileObject.seek(offset,position)
offset:
This is the position of the read/write pointer within the file. (number of characters)
position:
It has three values:
(this is optional and default value is 0)
0 : Start of the file
1 : Current position
2 : End of the file
Example:1
To create a binary file and store records into it
#to add a record in binary file
import pickle
import os
#function definition
def add_record():
try:
if os.path.isfile("stud1"):
f=open("stud1","ab")
else:
f=open("stud1","wb")
roll=int(input("Enter roll no "))
name=input("Enter name ")
name=name.upper()
per=float(input("Enter per "))
rec=[roll,name,per]
pickle.dump(rec,f)
print("Record added in file")
except EOFError:
f.close()
#function calling
add_record()
Example:2
To read a binary file and display all the records
#to display all the records
import pickle
#function definition
def std_dispall():
try:
f=open("stud1","rb")
while True:
rec=pickle.load(f)
print(rec)
except EOFError:
f.close()
except IOError:
print("Unable to open the file")
#function calling
std_dispall()
Example:3
To read a binary file and display all the records(Randomly)
#display a record using seek() and tell()
import pickle
#function definition
def std_dispall():
f=open("stud1","rb")
f.seek(0,0)
n=f.tell()
print("File pointer at(start of the file) ",n)
#rec=pickle.load(f)
#print(rec)
f.seek(0,2)
n=f.tell()
print("File pointer at(end of the file) ",n)
#rec=pickle.load(f)
#print(rec)
try:
f=open("stud1","rb")
f.seek(0,0)
while True:
rec=pickle.load(f)
n=f.tell()
print("File pointer at ",n)
print(rec)
except EOFError:
f.close()
except IOError:
print("Unable to open the file")
#function calling
std_dispall()




