Sub topic 12
Moving around a file with seek and tell
This chapter assumes you can open files with with open(...), know the difference between str and bytes, and have used the modes r, w, a and b. Here you will learn how to read the current position in a file and jump to another one.
The file position
An open file has a position, which is the offset where the next read or write happens. Opening a file in r or w mode puts the position at 0. Every read() or write() moves it forward. Two methods give you direct control:
f.tell()returns the current position.f.seek(offset, whence)moves the position.whencedefaults to 0.
| `whence` | Meaning | Constant |
|---|---|---|
| 0 | `offset` counts from the start of the file | `os.SEEK_SET` |
| 1 | `offset` counts from the current position | `os.SEEK_CUR` |
| 2 | `offset` counts from the end of the file | `os.SEEK_END` |
In binary mode the offset is a number of bytes, so all three values work with any offset.
with open("demo.bin", "wb") as f:
f.write(b"0123456789")
with open("demo.bin", "rb") as f:
print(f.tell()) # 0
f.seek(4)
print(f.read(3)) # b'456'
print(f.tell()) # 7
f.seek(-2, 2) # two bytes before the end
print(f.read()) # b'89'
f.seek(-5, 1) # five bytes back from position 10
print(f.read(2)) # b'56'
f.seek(0) # rewind
print(f.read(1)) # b'0'seek() returns the new position, and seeking past the end is allowed. Reading there returns empty data.
Text mode is more restricted
In text mode the file is decoded, so a byte offset does not map to a character count. Python restricts what you may pass:
tell()returns an opaque number. Do not do arithmetic on it. Only pass it back toseek().seek(n)accepts only 0 or a value thattell()returned earlier.seek(0, 1)andseek(0, 2)are allowed. Any other offset withwhence1 or 2 raisesio.UnsupportedOperation.
This pattern, which saves a position and returns to it later, works in text mode:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("alpha\nbeta\ngamma\n")
with open("notes.txt", encoding="utf-8") as f:
f.readline() # skip "alpha"
mark = f.tell() # remember the start of "beta"
print(f.readline().rstrip()) # beta
f.seek(mark) # go back
print(f.readline().rstrip()) # beta again
f.seek(0)
print(f.read().count("\n")) # 3Writing at a position
Opening with r+ (or r+b) allows both reading and writing, and both use the same position. Writing overwrites the bytes at that position. It does not insert new data. truncate(size) cuts the file to size bytes.
with open("demo.bin", "wb") as f:
f.write(b"0123456789")
with open("demo.bin", "r+b") as f:
f.seek(2)
f.write(b"XX") # overwrites bytes 2 and 3
f.seek(0)
print(f.read()) # b'01XX456789'
f.truncate(5) # keep only the first five bytes
with open("demo.bin", "rb") as f:
print(f.read()) # b'01XX4'Common errors
- Forgetting to rewind. After writing in
w+orr+mode, the position is at the end, soread()returns an empty string. Callseek(0)first. - Seeking in append mode. In
amode every write goes to the end of the file, whatever you pass toseek(). You can still seek to read. - Using
tell()as a character count. In text mode the value is opaque. For files with multi-byte characters or\r\nline endings it will not equallen(text). - Expecting insertion. To insert in the middle, read the rest of the file, write the new data, then write the rest back. For larger files, write a new file instead.
Exercise
A file is opened with open("log.txt", "rb"). Write the call that moves to the last 10 bytes of the file. Then say why the same call fails if the file is opened in text mode.
Show answer
Use f.seek(-10, 2), which counts 10 bytes back from the end. In text mode, seek with whence 1 or 2 accepts only an offset of 0, because the file is decoded and a byte offset may fall in the middle of a character. The call raises io.UnsupportedOperation.