Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Writing to a File

Tags:

python

I've been having trouble with this for a while. How do I open a file in python and continue writing to it but not overwriting what I had written before?

For instance:

The code below will write 'output is OK'. Then the next few lines will overwrite it and it will just be 'DONE'

But I want both 'output is OK' 'DONE' in the file

f = open('out.log', 'w+')
f.write('output is ')
# some work
s = 'OK.'
f.write(s)
f.write('\n')
f.flush()
f.close()
# some other work
f = open('out.log', 'w+')
f.write('done\n')
f.flush()
f.close()

I want to be able to freely open and write to it in intervals. Close it. Then repeat the process over and over.

Thanks for any help :D

like image 421
user1431282 Avatar asked Dec 01 '22 04:12

user1431282


1 Answers

Open the file in append mode. It will be created if it does not exist and it will be opened at its end for further writing if it does exist:

with open('out.log', 'a') as f:
    f.write('output is ')
    # some work
    s = 'OK.'
    f.write(s)
    f.write('\n')

# some other work
with open('out.log', 'a') as f:
    f.write('done\n')
like image 111
eumiro Avatar answered Dec 09 '22 19:12

eumiro