Seek (), then read (), then write () in python
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 (useful) exception:
Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: [Errno 0] Error The same thing happens when opened with "r +".
Is this really supposed to fail? What for?
Edit:
- Obviously, this is just an example, not what I'm actually trying to accomplish. My actual goal was to verify that the files end with "\ n" or add them before adding new lines.
- I work under Windows XP and they come up in Python 2.5 and Python 2.6.
I managed to work around the problem by calling the seek () function again:
f = open (r "myfile.txt", "a +")
f.seek (-1,2)
f.read ()
"BUT"
f.seek (-10,2)
f.write ('\ n')
The actual parameters of the second call request do not seem to matter.
This seems like a problem with Windows - see http://bugs.python.org/issue1521491 for a similar problem.
Better yet, a workaround given and explained at http://mail.python.org/pipermail/python-bugs-list/2005-August/029886.html , insert:
f.seek(f.tell()) between calls to read () and write ().
a + mode to add, if you want to read and write, you are looking for r +.
try the following:
>>> f = open("myfile.txt", "r+") >>> f.write('\n') Edit:
you should first indicate your platform ... there are known problems with searching in windows. When trying to search, UNIX and Win32 have different line endings, LF and CRLF, respectively. There is also a problem reading to the end of the file. I think you are looking for the seek (2) offset for the end of the file, and then continue from there.
These articles may interest you (the second is more specific):
http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-08/2512.html
http://mail.python.org/pipermail/python-list/2002-June/150556.html
Works for me:
$ echo hello > myfile.txt $ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open('myfile.txt', 'r+') >>> f.seek(-1, 2) >>> f.tell() 5L >>> f.read() '\n' >>> f.write('\n') >>> f.close() Are you at the windows? If so, try 'rb+' instead of 'r+' in mode.