Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add lines to existing file using python

Tags:

python

file

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

like image 730
user1246462 Avatar asked May 17 '12 17:05

user1246462


People also ask

How do I add more lines to a text file in Python?

Python write multiple lines to file. To write multiple lines to a file in Python, use a with open() function and then the writelines() function. The writelines() method writes the items of a list to the file. The texts will be inserted depending on the file mode and stream position.

How do you write to an existing file in Python?

In brief, any data can be read by Python. You can use the open(filename,mode) function to open a file. There are a set of file opening modes. To write in an existing file you have to open the file in append mode("a") , if the file does not exist, the file will be created.

Can you append to a file in Python?

In order to append a new line to the existing file, open the file in append mode, by using either 'a' or 'a+' as the access mode. The definition of these access modes is as follows: Append Only ('a'): Open the file for writing. The file is created if it does not exist.


2 Answers

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)

like image 102
Danica Avatar answered Oct 07 '22 05:10

Danica


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

with open('file.txt', 'a') as file:     file.write('input') 
like image 45
Jeff L Avatar answered Oct 07 '22 05:10

Jeff L