Sub topic 12
Moving around a file with seek and tell
Every open file has a current position, and read(), write() and readline() all start from it. This chapter covers the two methods that report and change that position, tell() and seek(). It also covers the restrictions text mode puts on them, and the patterns they enable: reading the end of a large file, random access by line, and overwriting data in place.
It assumes you can already open files with open(), choose a mode, use with, and tell str from bytes.
The file position
Think of a file as a row of bytes with a cursor between them. Opening a file in "r", "w" or "r+" mode puts the cursor at 0. Opening in "a" mode puts it at the end. Reading or writing n bytes moves the cursor forward by n.
f.tell()returns the current position.f.seek(offset, whence=0)moves the cursor and returns the new position.f.seekable()returnsTrueif the file supports seeking at all.
The whence argument says what offset is measured from:
| `whence` | Constant | Offset is measured from | Offset may be negative? |
|---|---|---|---|
| 0 (default) | `os.SEEK_SET` | Start of file | No |
| 1 | `os.SEEK_CUR` | Current position | Yes |
| 2 | `os.SEEK_END` | End of file | Yes, to go back from the end |
Prefer the named constants from os (or io) over bare numbers. f.seek(-3, os.SEEK_END) is easier to read than f.seek(-3, 2).
Seeking in binary mode
Binary mode gives you the full, simple behavior. Positions are byte counts, and all three whence values work.
import os
with open("demo.bin", "wb") as f:
f.write(b"0123456789")
with open("demo.bin", "rb") as f:
print(f.tell()) # 0
print(f.read(3)) # b'012'
print(f.tell()) # 3
f.seek(7) # absolute: byte 7
print(f.read(2)) # b'78'
f.seek(-2, os.SEEK_CUR) # back two bytes: position 7
print(f.read(1)) # b'7'
f.seek(-3, os.SEEK_END) # three bytes before the end
print(f.read()) # b'789'
print(f.seek(0, os.SEEK_END)) # 10, which is the file sizef.seek(0, os.SEEK_END) is a cheap way to get a file's size without os.stat. It returns the position it moved to.
Seeking in text mode
Text mode wraps the byte stream in a decoder, so a byte offset and a character offset are different things. UTF-8 characters take 1 to 4 bytes, and with default newline handling "\r\n" becomes a single "\n". Because of this, tell() in text mode returns an opaque number. Treat it as a bookmark and do not do arithmetic on it. For some encodings it also encodes decoder state.
Text mode therefore allows only these calls to seek():
seek(0), which goes to the start.seek(0, os.SEEK_END), which goes to the end.seek(0, os.SEEK_CUR), which does nothing useful but is allowed.seek(n)wherencame from an earliertell()on the same file.
import io
import os
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("h\u00e9llo\nworld\n")
with open("notes.txt", encoding="utf-8") as f:
f.readline() # consume "héllo\n"
mark = f.tell() # bookmark: start of "world"
f.read() # read to the end
f.seek(mark) # return to the bookmark
print(f.readline().rstrip()) # world
try:
f.seek(-3, os.SEEK_END) # nonzero end-relative seek
except io.UnsupportedOperation:
print("not allowed in text mode")If you need to jump to an arbitrary byte offset, open the file in "rb" and decode yourself.
tell() and iteration
In text mode, calling tell() while you iterate with for line in f raises OSError: telling position disabled by next() call. Iteration reads ahead in large chunks, so the reported position would be wrong. Use readline() in a loop instead:
with open("notes.txt", encoding="utf-8") as f:
while line := f.readline():
print(f.tell(), line.rstrip("\n"))In text mode tell() can be slow, because Python reconstructs the decoder state. Calling it on every line of a huge file is noticeably costly. In binary mode, track positions yourself by adding up len(line), as the next section shows.
Pattern: random access by line
If you read the same large file many times, scan it once to record where each line starts. Later you can jump straight to any line.
def index_lines(path):
"""Return the byte offset at which each line starts."""
offsets = []
pos = 0
with open(path, "rb") as f:
for line in f:
offsets.append(pos)
pos += len(line)
return offsets
def read_line(path, offsets, n):
with open(path, "rb") as f:
f.seek(offsets[n])
return f.readline().decode("utf-8").rstrip("\r\n")
with open("people.txt", "w", encoding="utf-8", newline="\n") as f:
f.write("Ada\nLinus\nGrace\nMargaret\n")
offsets = index_lines("people.txt")
print(offsets) # [0, 4, 10, 16]
print(read_line("people.txt", offsets, 2)) # GraceThe file is opened in binary mode, so offsets are real byte positions and len(line) counts bytes. The file is written with newline="\n" so the offsets above are the same on every platform.
Pattern: reading the end of a file
To print the last line of a multi-gigabyte log, do not read the whole file. Seek to the end and read backward in blocks until you have found a newline.
import os
def last_line(path, block=1024):
with open(path, "rb") as f:
pos = f.seek(0, os.SEEK_END)
data = b""
while pos > 0:
step = min(block, pos)
pos -= step
f.seek(pos)
data = f.read(step) + data
stripped = data.rstrip(b"\r\n")
if b"\n" in stripped:
break
return stripped.rsplit(b"\n", 1)[-1].decode("utf-8")
with open("app.log", "w", encoding="utf-8") as f:
for i in range(1, 501):
f.write(f"event {i}\n")
print(last_line("app.log")) # event 500Searching for b"\n" in raw bytes is safe for UTF-8. The byte 0x0A never appears inside a multi-byte character, so you cannot split a character by cutting at a newline. You only decode the final line, and it is complete once a newline precedes it.
Reading and writing the same file
Modes with + allow both operations on one file object:
"r+"opens an existing file without truncating it. The position starts at 0."w+"truncates the file first, then allows reading and writing."a+"allows reading and writing, but see the next section for how writes behave.
When you switch between reading and writing, call seek() first. Python's buffered classes cope without it, but an explicit seek makes the position unambiguous.
Writing does not change the file's length unless you write past the old end. Overwriting with shorter data leaves old bytes behind. Call truncate() to cut the file at the current position:
with open("status.txt", "w", encoding="utf-8") as f:
f.write("status: running\n")
with open("status.txt", "r+", encoding="utf-8") as f:
f.seek(0)
f.write("done\n")
f.truncate() # cut the file at the current position
with open("status.txt", encoding="utf-8") as f:
print(repr(f.read())) # 'done\n'Without f.truncate(), the file would hold 'done\ns: running\n'. truncate() does not move the position. truncate(size) cuts at an explicit byte size, and if size is larger than the file it extends the file.
Rewriting a file in place this way is not crash-safe. A failure partway through leaves a mixed file. For whole-file replacement use the temporary-file technique from the safe writes chapter.
Gotchas and failure modes
Append mode ignores seek for writes
In "a" and "a+" modes the operating system sends every write to the end of the file, whatever the current position is. You can seek to 0 and read, but you cannot overwrite earlier data.
with open("log.txt", "a+", encoding="utf-8") as f:
f.write("one\n")
f.seek(0)
print(f.read()) # reads from the start
f.seek(0)
f.write("two\n") # still appended at the endIf you need to overwrite in the middle, use "r+".
Seeking past the end
Seeking beyond the end of a file is allowed. Nothing changes until you write. A write there extends the file, and the gap is filled with zero bytes. On many file systems the gap is stored sparsely, so the file can look large without using that much disk space. Reading at a position past the end returns an empty result, not an error.
Landing in the middle of a character
A binary seek() to an arbitrary offset can land inside a multi-byte UTF-8 sequence. Decoding from there raises UnicodeDecodeError. UTF-8 continuation bytes look like 0b10xxxxxx, so you can skip forward until you reach a byte that does not match that pattern. Better, only seek to offsets you know are boundaries, such as the line starts from index_lines.
Files that cannot seek
Pipes, sockets and the terminal are not seekable. Calling seek() on them raises OSError ("Illegal seek") or io.UnsupportedOperation, and f.seekable() returns False. Standard input is a common case: sys.stdin.seek(0) fails when input is piped. Compressed files from gzip support seek(), but moving backward means decompressing from the start again, so it is slow.
Two handles on one file
Each file object has its own position and its own write buffer. If one handle writes and another reads the same file, the reader will not see the data until the writer calls flush() or closes. Both handles also move independently, so seeking one does not move the other.
Choosing an approach
| Goal | Use |
|---|---|
| Read a file once, front to back | Plain iteration, no seek |
| Reread from the beginning | `seek(0)`, or reopen the file |
| Jump to a byte offset | Binary mode and `seek(offset)` |
| Read the tail of a large file | Binary mode and `seek(-n, os.SEEK_END)`, or the backward loop above |
| Many lookups by line number | One pass to build an offset index, then `seek()` and `readline()` |
| Resume text reading later | Save the `tell()` value and `seek()` back to it on the same file |
| Replace a whole file safely | A temporary file and `os.replace`, not seek |
Exercise
A script opens a UTF-8 text file with open("data.txt", encoding="utf-8") and calls f.seek(-10, 2) to read the last 10 characters. What happens, and how do you fix it?
Show answer
It raises io.UnsupportedOperation, because text mode does not allow nonzero offsets relative to the end (whence=2). Open the file in "rb", call f.seek(-10, os.SEEK_END), and read the bytes. Decode them afterward. For multi-byte text the last 10 bytes may not be 10 characters, and the first byte could be mid-character, so read a larger block, decode it, and take the last 10 characters of the result.
Exercise
A file contains "status: running\n" (16 bytes). You open it with "r+", write "ok\n" at position 0, and close it without any other call. What does the file contain, and what one call would give you "ok\n"?
Show answer
The file contains "ok\ns: running\n". Writing replaces only the first 3 bytes, and the rest of the old data stays. Calling f.truncate() after the write cuts the file at the current position (3), leaving "ok\n".
Exercise
You open a log in "a+" mode, call f.seek(0), and then f.write("header\n") hoping to insert a header at the top. Where does the text end up, and which mode should you use to overwrite at an arbitrary position?
Show answer
It is appended at the end of the file, because append mode always writes at the end regardless of seek. Use "r+" (or "rb+" for bytes). Note that this overwrites existing bytes and does not insert, so inserting a header means rewriting the file, ideally through a temporary file and os.replace.