How to use writelines to append new lines to an existing file

N

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.

My first try was:
'456'

I supposed to have:'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
 
G

Grigoris Tsolakidis

Use
file = open(open('/tmp/myfile', 'a')) the second time
when you want to append line
 
M

Max Erickson

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:

'456'

I supposed to have:
'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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top