Add lines to existing file using Python
Asked Answered
G

4

78

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

Gluey answered 17/5, 2012 at 17:47 Comment(1)
Do not use "file" as variable name because it's shadowing the built-in file typeDementia
M
79

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)

Montespan answered 17/5, 2012 at 17:49 Comment(0)
S
80

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

with open('file.txt', 'a') as file:
    file.write('input')
Sump answered 17/5, 2012 at 17:50 Comment(1)
Note! This will not add a newline. If you need to add a line to a text file (as opposed to a line fragment), end the data with \n, e.g.: file.write('input\n')Stalder
M
79

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)

Montespan answered 17/5, 2012 at 17:49 Comment(0)
I
21

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')
Incognito answered 17/5, 2012 at 17:50 Comment(0)
A
0

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')
Ammoniate answered 28/6, 2023 at 23:51 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.