You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.6.3中seek函数非零末尾相对偏移报错问题咨询

Why does 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=2 in 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:

  1. Read the entire file content in text mode
  2. Modify the string directly
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:45:52