File pointers are crucial in file I/O operations as they indicate the current position in the file. Python provides built-in methods like seek()
and tell()
to control and monitor this position, enabling random access to file content.
tell()
: Returns the current position of the file pointer.seek(offset, whence)
: Moves the file pointer to a specific byte position.
0
: from the beginning (default)1
: from the current position2
: from the end of the fileseek()
to read or write at a specific byte location.seek()
works by bytes, specific lines can be reached by looping with counters or using linecache
.with open('example.txt', 'r') as file:
print("Current position:", file.tell())
file.read(10)
print("Position after reading 10 chars:", file.tell())
with open('example.txt', 'r') as file:
file.seek(5)
print(file.read(10)) # Reads 10 characters from 6th character
with open('example.txt', 'rb') as file:
file.seek(-10, 2)
print(file.read()) # Last 10 bytes
with open('example.txt', 'r') as file:
print(file.read(5))
file.seek(0)
print(file.read(5))
def read_from(file_path, start, length):
with open(file_path, 'r') as file:
file.seek(start)
return file.read(length)
print(read_from('example.txt', 10, 15))
File pointers work in bytes, not lines. To go to a specific line (e.g., line 100), you generally need to iterate through lines. However, efficient techniques exist to avoid reading the entire file into memory.
def read_line(filepath, line_number):
with open(filepath, 'r') as file:
for current_line, line in enumerate(file, start=1):
if current_line == line_number:
return line.strip()
return None
print(read_line('example.txt', 5))
import linecache
line = linecache.getline('example.txt', 10)
print("Line 10:", line.strip())
Note: linecache
caches file lines in memory and is best used for quick access to known line numbers, especially in larger files.
from itertools import islice
with open('example.txt', 'r') as file:
target_line = next(islice(file, 9, 10), None) # 10th line (index 9)
print("Line 10:", target_line.strip())