Random Access in File
All the file
manipulation functions discussed till now are used to access the data sequentially
from a file i.e from beginning.
When it is
required to access data in a random fashion from any position, the seek() and tell() functions of Python are used.
The seek() and
tell() methods are used to manipulate the file pointer of a file.
A file pointer
is logical marker which keeps track of the number of bytes read or written in a
file.
•
When
the file is opened in the read mode (“r”), the
file pointer is positioned at 0th byte and the
pointer automatically moves after every read or write operation.
•
Similarily,
when the file is opened in append mode, it is
positioned at the end of file.
•
The
file operation starts from the position of the file handle
Random Access in File - seek() Method
seek() method is used to change the position of the File
Handle to a given specific position.
Syntax : file_object.seek(offset, [reference_point])
• offset
-
no. of bytes (integer) by which the file object is to be moved.
• reference_point
-
indicates the starting position of the file object from
which the file handle will move.
The reference point can have any of the following values:
1
- beginning
of the file
2
- current
position of the file
3
- end
of file
The reference point refers to the position from which the
offset has to be counted i.e Offset is added to reference point to position the
file handle.
The reference point is optional in seek(). When not given,
by default, the value of reference_point is taken as 0, i.e. the offset is counted
from the beginning of the file.
Note :
The values of reference point 1 and 2 work only, if the
file has been opened for binary mode
EG:
#Use of seek()
file = open("text.txt","w")
file.write("This program is creating a text
file\n")
file.close()
file = open("text.txt","r")
file.seek(8) #file pointer positioned at 8th
byte –(g of program)
str= file.read(4) # 4 characters read from current
position (gram)
print(str) #Display gram
file.seek(5) #file
pointer positioned at 5th byte (on p of program)
print(file.read()) #file read from 5th position
till end of file
file.seek(0) #file pointer positioned at beginning
print(file.read(12)) # 12 characters read from 0th
byte
file.close()
OUTPUT:
gram
This program
with open("Test.txt",'w') as F:
F.write("abcdefghi\n")
with open("Test.txt",'r') as F:
for i in range(4):
F.seek(i)
print(F.read(i+1))
Random
Access in File -tell() Method
The tell() method returns an integer giving the
current position of file object in the file.
The integer returned specifies the number of bytes
from the beginning of the file till the current position of file object.
Syntax:fileobject.tell()
Example:fin =
open("text.txt","r")
print(fin.tell())
Output:0
When the file is opened in the reading mode, the file
handle is positioned in the 0thbyte i.ethe beginning of the file. Hence, the
output is 0
Similarly, when the file is opened in append mode, the
file handle is positioned at the end of the file. Hence the statement print(fin.tell())
can be used to display the size of the file.
Random Access in File -tell() Method
file = open("sample.txt", "w+") #w+ Opens the file for both writing and
reading
file.write("Hello World")
print("Current position:", file.tell()) # After writing
file.seek(0) #
Move to beginning
print("Position after seek(0):",
file.tell())
data = file.read(5)
# Read 5 characters
print("Data Read:", data)
print("Position after reading 5
characters:", file.tell())
file.close()
Meaning of "w+" Mode:
- Opens
the file for both writing and reading.
- Creates
the file if it does not exist.
- Overwrites the file (deletes
all existing content) if it already exists.
- The file pointer is placed at the beginning of the file.
f = open("sample.txt", "w+")
# Write to the file
f.write("Hello World\n")
f.write("Welcome to Python")
# Move pointer back to the beginning
f.seek(0)
# Read the contents
content = f.read()
print("File content:\n", content)
f.close()
#Without seek(0), the read() would print nothing, because the pointer would be at the end of the file after writing.
Eg:
f = open("file.txt", "w+")
f.write("Example text")
print(f.read()) # ❌ Will print nothing — pointer is at end
Correct Code:
f.seek(0)
print(f.read())
r+ Mode in Python File Handling:
The r+ mode is used to open a file for both
reading and writing.
· The file must already exist. If it does not, Python will raise a FileNotFoundError.
· The file pointer is placed at the beginning of the file.
· You can read from and write to the file.
· When you write, it overwrites the content from the current file pointer onward (it doesn't insert).
EG:
f1=open("text.txt","r+")
print(f1.read())
str=input("Enter string:")
f1.write(str+'\n')
f1.seek(2)
print("The new content")
print(f1.read())
f1.close()
·
When you write, it overwrites the content from the current file pointer
onward (it doesn't insert).
"r" |
Read only (default) |
"w" |
Write only (overwrites file) |
"a" |
Append only |
"r+" |
Read + Write (doesn't delete content) |
"w+" |
Write + Read (deletes content) |
"a+" |
Append + Read (keeps content, adds to end) |
Comments
Post a Comment