简体   繁体   中英

how to add lines to existing file using python

I already created a txt file using python with a few lines of text that will be read by a simple program. However, I am having some trouble reopening the file and writing additional lines in the file in a later part of the program. (The lines will be written from user input obtained later on.)

with open('file.txt', 'w') as file:
    file.write('input')

This is assuming that 'file.txt' has been opened before and written in. In opening this a second time however, with the code that I currently have, I have to erase everything that was written before and rewrite the new line. Is there a way to prevent this from happening (and possibly cut down on the excessive code of opening the file again)?

If you want to append to the file, open it with 'a' . If you want to seek through the file to find the place where you should insert the line, use 'r+' . ( docs )

Open the file for 'append' rather than 'write'.

with open('file.txt', 'a') as file:
    file.write('input')

Use 'a' , 'a' means append . Anything written to a file opened with 'a' attribute is written at the end of the file.

with open('file.txt', 'a') as file:
    file.write('input')

The answers above are correct, but to append the data as a new line, as opposed to tacking it onto the end of the last line in the file, use the following:

with open('file.txt', 'a') as file:
    file.writelines('input')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM