When running the following python code:
>>> f = open(r"myfile.txt", "a+")
>>> f.seek(-1,2)
>>> f.read()
'a'
>>> f.write('\n')
I get the following (helpful) exception:
Traceback (most recent call last):
File "", line 1, in
IOError: [Errno 0] Error
The same thing happens when openning with "r+".
Is this supposed to fail? Why?
Edit:
Obviously, this is just an example, not what I am actually trying to execute. My actual goal was to verify that the files ends with "\n", or add one, before adding the new lines.
I am working under Windows XP, and they problem exists in both Python 2.5 and Python 2.6.
I managed to bypass the problem by calling seek() again:
f = open(r"myfile.txt", "a+")
f.seek(-1,2)
f.read()
'a'
f.seek(-10,2)
f.write('\n')
The actual parameters of the 2nd seek call don't seem to matter.
解决方案
This appears to be a Windows-specific problem - see http://bugs.python.org/issue1521491 for a similar issue.
f.seek(f.tell())
between the read() and write() calls.