By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,100 Members | 2,958 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,100 IT Pros & Developers. It's quick & easy.

File read-write mode: problem appending after reading

P: n/a
Hi all,

Working with read and write operations on a file I stumbled on a
complication when writes fail following a read to the end.
>>f = file ('T:/z', 'r+b')
f.write ('abcdefg')
f.tell ()
30L
>>f.seek (0)
f.read ()
'abcdefg'
>>f.flush () # Calling or not makes no difference
f.write ('abcdefg')
Traceback (most recent call last):
File "<pyshell#62>", line 1, in -toplevel-
f.write ('abcdefg')
IOError: (0, 'Error')

Flushing doesn't help. I found two work arounds:
>>f.read ()
'abcdefg'
>>f.read () # Workaround 1: A second read (returning an empty string)
''
>>f.write ('abcdefg')
(No error)
>>f.read ()
'abcdefg'
>>f.seek (f.tell ()) # Workaround 2: Setting the cursor (to where
it is!)
>>f.write ('abcdefg')
(No error)

I found no problem with writing into the file. So it looks like it has
to do with the cursor which a read puts past the end, unless it is past
the end, in which case it goes back to the end. Is there a less kludgy
alternative to "fseek (ftell ())"?

Frederic

Oct 13 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.