Python 3.6.3中seek函数非零末尾相对偏移报错问题咨询
seek(-5, 2) throw an error even though help() says offset can be negative? Hey there! Let's break down why you're hitting this UnsupportedOperation error. The root cause comes down to the file mode you're using and how Python handles text vs. binary file objects.
1. Text mode imposes restrictions on end-relative seeks
You opened your file with 'w', which is Python's text write mode. For text-mode file objects, there's an intentional limitation when using seek() with whence=2 (meaning "seek relative to the end of the file"): you can only use an offset of 0.
This isn't a bug—it's a design choice. Text files use character encodings that often include multi-byte characters, so calculating an exact position relative to the end isn't reliably possible. Python blocks non-zero end-relative seeks in text mode to avoid ambiguous or incorrect positioning.
2. Why help(f.seek) says negative offsets are allowed
The help text isn't misleading! Negative offsets are supported in valid scenarios:
- When using
whence=0(seek relative to the start of the file), as long as the offset doesn't move before the file's beginning. - When using
whence=1(seek relative to the current position), again as long as you don't go beyond the file's start. - When using
whence=2in binary mode (we'll cover this next).
3. Fixing the error: Switch to binary mode
If you need to seek relative to the end with a non-zero offset, use binary write mode ('wb'). Binary mode operates on raw bytes, so there's no encoding ambiguity to complicate position calculations. Here's your adjusted working code:
f = open('New_file.txt', 'wb') f.write(b'This is a text') # Write bytes instead of a string f.seek(-5, 2) print(f.tell()) # Outputs 8 (total byte length is 14, 14-5=8) f.close()
4. Alternative for text content
If you're working with text and need to edit positions relative to the end, a common workaround is:
- Read the entire file content in text mode
- Modify the string directly
- Write the updated content back to the file.
Or, if you just need to append content, use the 'a' (append) mode—it automatically positions the file pointer at the end without needing seek().
内容的提问来源于stack exchange,提问作者davejason

