[Tutor] Read and write from file

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Aug 26 10:24:04 CEST 2004


> The file has the following lines:
>
> 1
> 2
> 3
> 4
> 5
....

Actually it has the following bytes:

1,\n,2,\n,3,\n,4,\n,5,\n.....

You open the file and the file pointer, or cursor, is pointing at the
1.
You print up to the first newline character which gets you 1,\n
You write the four characters tests which overwrite 2,\n,3,\n.
You print up to the next newline which gives you 4\n....

Every operation moves the pointer along the file. If you want
to overwrite the first line you must work out the length of
that line then relocate to the beginning of it and write out
exactly the right number of bytes.

At least that's what I'd expect to happen, and what seems to happen
for you. When I did some experimenting I got something else!
If I open the file (using open(foo,'r+)) and immediately write
to it I get what I would expect, it overwrites the first few bytes.
But if I readline() first and then write() it appends the output
at the end of the file... I don't know why!

But if I use file.seek() to position the pointer explicitly and
then write, it works as expected. So it looks like that's the reliable
way to do it.

Also you must flush the buffer immediately after writing, if you
read anything first it will negate your write.

> ... tried both fil.close and fil.flush without any luck.

use the sequence

fil.write()
fil.flush()
fil.close()


> What I really want to do is to read the first line, 1, then replace
that
> with something else, or remove it.

Note you can only replace it and you must write the same number
of characters.

A much easier approach is to use two files, effectively copying
the data from one to the other amending as you go. There is an
example of this in the file handling topic of my tutor.

FWIW Here is my test session:

>>> f=open('test.dat','r+')
>>> f.write('Overwrite')
>>> f.flush()
>>> f.readline()
'4\r\n'
>>> f.seek(0)
>>> f.read()
'Overwrite4\r\n5\r\n6\r\n7\r\n8\r\n9\r\ntesttestingtest-2'
>>> f.seek(12)
>>> f.write('silly')
>>> f.flush()
>>> f.seek(0)
>>> f.read()
'Overwrite4\r\nsilly\n7\r\n8\r\n9\r\ntesttestingtest-2'
>>> f.close()
>>>

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld/tutor2/



More information about the Tutor mailing list