运行以下python代码时:
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n')
Run Code Online (Sandbox Code Playgroud)
我得到以下(有用)例外:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 0] Error
Run Code Online (Sandbox Code Playgroud)
用"r +"打开时会发生同样的事情.
这应该失败吗?为什么?
编辑:
我设法通过再次调用seek()来绕过这个问题:
f = open(r"myfile.txt","a +")
f.seek(-1,2)
f.read()
'
a'f.seek(-10,2)
f.write('\n')
第二次搜索呼叫的实际参数似乎并不重要.
这似乎是特定于Windows的问题 - 有关类似问题,请参阅http://bugs.python.org/issue1521491.
更好的是,在http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html上给出并解释了一个解决方法,插入:
f.seek(f.tell())
Run Code Online (Sandbox Code Playgroud)
read()和write()之间的调用.