Skip to content

Computer Science · Ch 2 — File Handling in Python

The seek() method

2.6.2

The seek() method

The seek() method lets you move the file object to a specific byte position inside a file. This is essential when you need to read from or write to a particular location without going through the entire file sequentially.

The syntax is:

file_object.seek(offset [, reference_point])

Here, offset is the number of bytes you want to move the file object. The reference_point tells Python where to start counting that offset from. It can take one of three values:

  • 0 — beginning of the file (this is the default)
  • 1 — current position of the file object
  • 2 — end of the file

If you don't specify a reference_point, Python assumes it is 0. So fileObject.seek(5) is the same as fileObject.seek(5, 0), and it will place the file object at the 5th byte from the start of the file.

The textbook gives a concrete example: the statement fileObject.seek(5,0) positions the file object at the 5th byte from the beginning.

Watch out

The seek() method does not work the same way for text files and binary files. In text files, only reference_point 0 is guaranteed to work reliably. Using 1 or 2 with a text file may cause unexpected behaviour or errors, especially if the file contains multi-byte characters (like in Unicode). For binary files, all three reference points work as expected.

Program 2-2: Application of seek() and tell()

The textbook demonstrates this with a complete program. Here is what it does, step by step:

  1. A file named testfile.txt is opened in "r+" mode (read and write, without truncating).
  2. The entire content is read and printed. The file contains the line: roll_numbers = [1, 2, 3, 4, 5, 6]
  3. tell() is called to show the current position — it returns 33, meaning the file object is at the 33rd byte (the end of the file, after reading everything).
  4. seek(0) moves the file object back to the very beginning. tell() confirms the position is now 0.
  5. seek(10) moves the file object to the 10th byte from the start. tell() confirms the position is 10.
  6. read() is called again. This time, it reads from byte 10 onwards, which outputs: rs = [1, 2, 3, 4, 5, 6] …