Working with File Pointers in Python
File pointers allow precise control over where to read or write in a file. Python provides the seek()
and tell()
methods for efficient file manipulation.
The tell()
Method
The tell()
method returns the current position of the file pointer. The position is measured in bytes from the start of the file.
Syntax
file.tell()
Example
with open("example.txt", "r") as file:
content = file.read(10) # Read the first 10 bytes
print("Pointer position after reading 10 bytes:", file.tell())
The seek()
Method
The seek()
method moves the file pointer to a specified position. This allows you to control where reading or writing begins.
Syntax
file.seek(offset, whence)
offset
: The number of bytes to move the pointer.whence
(optional): Reference position foroffset
.0
(default): Start of the file.1
: Current file pointer position.2
: End of the file.
Example
with open("example.txt", "r") as file:
file.seek(5) # Move to the 5th byte
print("Pointer position:", file.tell())
content = file.read(5) # Read 5 bytes from the 5th byte
print("Content:", content)
Combining seek()
and tell()
You can use seek()
and tell()
together to navigate and monitor the file pointer’s position.
Example
with open("example.txt", "r") as file:
print("Initial pointer position:", file.tell())
file.seek(10) # Move to the 10th byte
print("Pointer position after seek:", file.tell())
content = file.read(5) # Read 5 bytes
print("Read content:", content)
print("Pointer position after reading:", file.tell())
Use Cases for File Pointers
- Random Access: Efficiently read or write data at specific positions in large files.
- File Modification: Update specific parts of a file without overwriting the entire content.
- Data Parsing: Navigate structured files (e.g., logs, CSVs) for precise data extraction.
Try It Yourself
Problem 1: Find Pointer Position After Reading
Write a program to open a file, read the first 20 characters, and print the pointer position.
Show Solution
with open("example.txt", "r") as file:
content = file.read(20)
print("Pointer position after reading 20 characters:", file.tell())
Problem 2: Navigate to the Middle of a File
Write a program to move the pointer to the middle of a file and print the content from that position.
Show Solution
with open("example.txt", "r") as file:
file.seek(0, 2) # Move to the end to get file size
file_size = file.tell()
middle = file_size // 2
file.seek(middle) # Move to the middle
print("Content from the middle:", file.read(20))
File pointers give you unparalleled control over file operations. Experiment with seek()
and tell()
to build a solid foundation in file handling!