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
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With