Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding data to end of existing file python

Tags:

python

file-io

So my code looks like this .... but I want to add data always to the end of the document how would I do this

try:
    f = open("file.txt", "w")
    try:
        f.write('blah') # Write a string to a file
        f.writelines(lines) # Write a sequence of strings to a file
    finally:
        f.close()
except IOError:
    pass
like image 800
Jimbo Mombasa Avatar asked Dec 03 '22 00:12

Jimbo Mombasa


2 Answers

Open the file using 'a' (append) instead of 'w' (write, truncate)

Besides that, you can do the following isntead of the try..finally block:

with open('file.txt', 'a') as f:
    f.write('blah')
    f.writelines(lines)

The with block automatically takes care about closing the file at the end of the block.

like image 118
ThiefMaster Avatar answered Dec 20 '22 07:12

ThiefMaster


open the file with "a" instead of "w"

like image 26
sizzzzlerz Avatar answered Dec 20 '22 09:12

sizzzzlerz