How to use writelines to append new lines to an existing file
Max Erickson
maxerickson at gmail.com
Thu Sep 22 09:36:29 EDT 2005
Nico Grubert <nicogrubert at gmail.com> wrote in
news:mailman.781.1127393534.509.python-list at python.org:
> Hi there,
>
> I would like to open an existing file that contains some lines of
> text in order to append a new line at the end of the content.
>
> My first try was:
>
> >>> f = open('/tmp/myfile', 'w') #create new file for writing
> >>> f.writelines('123') #write first line
> >>> f.close()
> >>> f = open('/tmp/myfile', 'w') #open existing file to append
> >>> new line f.writelines('456')
> >>> f.close()
> >>> f = open('/tmp/myfile', 'r') # open file for reading
> >>> f.read()
> '456'
>
> I supposed to have:
> >>> f.read()
> '123\n456\n'
>
>
> Does f = open('/tmp/myfile', 'w') overwrite the existing file
> or does f.writelines('456') replace the first line in the
> existing file?
>
> Nico
There is a good explanation in the tutorial:
http://docs.python.org/tut/node9.html#SECTION009200000000000000000
and more detail is available in the docs for builtin functions:
http://docs.python.org/lib/built-in-funcs.html
(look under file() but probably still use open())
That said, open(file, 'a') will open an existing file to append.
max
More information about the Python-list
mailing list