Discussion:
How to use writelines to append new lines to an existing file
(too old to reply)
Nico Grubert
2005-09-22 12:52:06 UTC
Permalink
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.
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'
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
Grigoris Tsolakidis
2005-09-22 13:02:45 UTC
Permalink
Use
file = open(open('/tmp/myfile', 'a')) the second time
when you want to append line
Post by Nico Grubert
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.
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'
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
Tom Brown
2005-09-22 13:25:32 UTC
Permalink
Post by Nico Grubert
Does f = open('/tmp/myfile', 'w') overwrite the existing file or
does f.writelines('456') replace the first line in the existing file?
Here's an excerpt from open.__doc__

The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending. The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.


Tom
Max Erickson
2005-09-22 13:36:29 UTC
Permalink
Post by Nico Grubert
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.
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'
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

Continue reading on narkive:
Loading...