File Pointers and Positioning in Python

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.

Key Concepts

Examples: File Pointers and Positioning

Example 1: Get current file position

with open('example.txt', 'r') as file:
    print("Current position:", file.tell())
    file.read(10)
    print("Position after reading 10 chars:", file.tell())

Example 2: Move file pointer to a specific position

with open('example.txt', 'r') as file:
    file.seek(5)
    print(file.read(10))  # Reads 10 characters from 6th character

Example 3: Move pointer relative to end (binary mode)

with open('example.txt', 'rb') as file:
    file.seek(-10, 2)
    print(file.read())  # Last 10 bytes

Example 4: Rewind and reread

with open('example.txt', 'r') as file:
    print(file.read(5))
    file.seek(0)
    print(file.read(5))

Example 5: Random access read

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))

Going to a Specific Line in a File

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.

Example 6: Read a specific line by number

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))

Example 7: Using linecache for direct line access

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.

Example 8: Skip to line using itertools

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())