[Tutor] read, write to file
Alan Gauld
alan.gauld@blueyonder.co.uk
Mon Jul 21 18:49:02 2003
> f=open('C:/Python22/Tools/tmp/workfile.txt', 'w')
> f.write('This is the first line of the file')
>
> after it finally seemed to work I tried to read the line with
readline()
You don't show us that code so its hard to be sure, however you
should close the file between writing and reading, or if you open
it for both you need to remember to reset the file pointer back
to the beginning with f.seek(0), you might also need to force
the write with f.flush()
> What I got was several hundred lines of x's and o's, but nothing was
written
> to the file
Did you actually check the file by opening it in wordpad or
some other text editor? Or are you just assuming that because
you didn't see it in the output that it wasn't written?
If you checked in wordpad then its probably a missing close/flush().
If you only looked at the output it could be there but you
didn't reset the file pointer to the beginning...
> last week I went through the same thing and after rebooting several
times it
> finally decided to work,
This sounds like a missing flush/close issue, the OS eventually writes
the buffered data and one time you got lucky in your timing...
> it seems to me that there is something
> fundamentally wrong with the read, write to file functions in this
latest
> version of python.
Nope, all versions of Python(and most other languages) work
the same way with buffered file I/O. Its actually a good thing
because it significantly improves the speed of file operations,
but it does require a little bit of good housekeeping on occasion.
Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld