PythonFile HandlingWorking with File Pointers

Navigating Files: The File Pointer (seek and tell)

When you open a file, Python maintains an internal file pointer (or cursor) that keeps track of your current position. Every time you read or write data, this pointer moves forward. While sequential access is often enough, sometimes you need to jump to specific locations within a file. This is known as random access, and it’s controlled by the seek() and tell() methods.

tell(): “Where Am I?”

The .tell() method is straightforward: it returns an integer representing the file pointer’s current position in bytes from the beginning of the file.

Pyground

Create a file and use `tell()` to track the pointer's position as you read from it.

Expected Output:

Initial position: 0\nRead 'The journey'. New position: 11\nRead ' of a thou'. New position: 21

Output:

seek(): “Go Here”

The .seek() method allows you to move the file pointer to a specific location. Its syntax is seek(offset, whence=0).

  • offset: The number of bytes to move.
  • whence: The reference point for the offset. It has three possible values:

whence=0 (Default): Absolute Positioning

This moves the pointer to the offset number of bytes from the beginning of the file. This is the most common way to use seek().

Pyground

Use `seek()` with `whence=0` to jump to the word 'thousand' and read from there.

Expected Output:

Pointer is now at: 22\nRead from new position: 'sand miles begins with a single step.'

Output:

⚠️

Text Files vs. Binary Files

  • When a file is opened in text mode, seek() only allows whence=0 (except for seek(0, 2) which seeks to the end). This is because variable-width character encodings (like UTF-8) make it impossible to know the byte position of a specific character without reading from the start.
  • When a file is opened in binary mode ('rb'), you can use all three whence modes freely, as one byte always corresponds to one unit of data.

For reliable random access, binary mode is often preferred.

Practical Use Case: Modifying a File in Place

seek() is essential when you need to modify a small part of a file without rewriting the entire thing. This is common when working with files that have fixed-size records.

Pyground

Create a binary file of records. Then, use `seek()` to jump to the second record and update its value.

Expected Output:

File content after update: b'REC1\\nREC2cREC3\\x0c'\nValue of second record: 99

Output: