Read file, and append?

John Machin sjmachin at lexicon.net
Wed Dec 26 18:17:51 EST 2007


On Dec 27, 9:04 am, Gilles Ganault <nos... at nospam.com> wrote:
> On Tue, 25 Dec 2007 13:27:09 -0800, Dennis Lee Bieber
>
> <wlfr... at ix.netcom.com> wrote:
> >Ignoring the question of the proper I/O mode, I believe the I/O
> >system MAY require one to perform a seek() when switching from read to
> >write and vice versa...
>
> I thought about this, but I don't understand why I would need to do
> this:
>
> myfile=open('test.txt','r+')
> content = myfile.read()
> myfile.seek()

The above would not execute; seek needs at least one argument.
"Perform a seek()" was an abbreviated way of telling you to seek to
the position at which you want to write i.e. (current) end of file so
you would use seek(0, 2).

"Why": already explained; some stdio implementations require it.

> myfile.write('added this')
> myfile.close
>
> Is there really no way to read from a file and append data to it while
> keeping the file open?
>
> Also, I noticed a problem with the code given by Garry: When opening a
> file in binary mode, the EOF character is 0A, while Windows apps
> expect 0D0A. VisualBasic was not happy :-)

I'm sorry, but your statement of the alleged problem doesn't make much
sense. Possibly you mean EOL (end of line), not EOF (end of file). In
any case, when opening a file in binary mode, lines (and end-of-line
conventions) are quite irrelevant -- you use a_string = f.read(nbytes)
to read (or f.write(a_string) to write) as many bytes as you think you
need, starting at the current position in the file.

Perhaps if you provided more precise information than "VisualBasic was
not happy", like: the exact code that you ran, and the exact [hint:
use the repr() function] contents of the two input files and the
output file, plus what you expected the contents of the output file to
be, plus whatever VB had to say about the output file, we might be
able to help you with the problem.

Cheers,
John




More information about the Python-list mailing list