user1246462
user1246462

Reputation: 1268

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)?

Upvotes: 79

Views: 226179

Answers (4)

Asclepius
Asclepius

Reputation: 63282

If having a pathlib.Path object (instead of a str object), consider using its open method.

with my_path.open(mode='a') as file:
    file.write(f'{my_line}\n')

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250921

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')

Upvotes: 21

Jeff L
Jeff L

Reputation: 6188

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

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

Upvotes: 83

Danica
Danica

Reputation: 28846

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)

Upvotes: 79

Related Questions