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 "<stdin>", line 1, in <module>
IOError: [Errno 0] Error
The same thing happens when openning with "r+".
Is this supposed to fail? Why?
Edit:
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.
Even better, a workaround given and explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html, insert:
f.seek(f.tell())
between the read() and write() calls.
the a+ mode is for appending, if you want to read & write, you are looking for r+.
try this:
>>> f = open("myfile.txt", "r+")
>>> f.write('\n')
Edit:
you should have specified your platform initially... there are known problems with seek within windows. When trying to seek, UNIX and Win32 have different line endings, LF and CRLF respectively. There is also an issue with reading to the end of a file. I think you are looking for the seek(2) offset for the end of the file, then carry on from there.
these articles may be of interest to you (the second one more specifically):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html
http://mail.python.org/pipermail/python-list/2002-June/150556.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With