Reading a file and then writing something back

Remy Blank remy.blank_asps at pobox.com
Wed Jul 21 16:40:17 CEST 2004


Kevin T. Ryan wrote:
> I'm not sure, but I'm wondering if this is a bug, or maybe (more
> likely) I'm misunderstanding something...see below:
> 
> 
>>>>f = open('testfile', 'w')
>>>>f.write('kevin\n')
>>>>f.write('dan\n')
>>>>f.write('pat\n')
>>>>f.close()
>>>>f = open('testfile', 'r+')
>>>>f.readline()
> 
> 'kevin\n'
> 
>>>>f.readline()
> 
> 'dan\n'
> 
>>>>f.write('chris\n')
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> IOError: (0, 'Error')

This is just a guess, I don't know the inner workings of files in 
Python, but here we go:

I think that readline() doesn't read one character at a time from the 
file, until it finds a newline, but reads a whole block of characters, 
looks for the first newline and returns that string (for efficiency 
reasons). Due to this buffering, the file pointer position is undefined 
after a readline(), and so a write() afterwards doesn't make sense. 
Python tries to help you not to fall into this trap.

> I've figured out that I can do an open('testfile', 'r+') and then seek
> and write something (without an error), but it just seems odd that I
> would get an IOError for what I was trying to do.

When you do a seek(), the file pointer position is clearly defined, so a 
write() makes sense.

A tentative solution could be:

pos = f.tell()
s = f.readline()         # Reads 'dan\n'
f.seek(pos + len(s))
f.write('chris\n')

However, I'm not sure you want to do that, as the string written will 
just overwrite the previous content, and will probably not be aligned 
with the next newline in the file. Except if you don't care about the 
data following your write.

Hope this helps.
-- Remy


Remove underscore and anti-spam suffix in reply address for a timely 
response.



More information about the Python-list mailing list