Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

start iteration from a specific line in a text file in python

Tags:

python

Assume I have a text file (named test.txt) that I have wrote 15 lines into it before in my Python script. Now, I want to append some lines to that file. How can I start iteration from line #16 of test.txt and append some new lines to it in Python?

like image 942
user1581399 Avatar asked Feb 03 '26 13:02

user1581399


1 Answers

To append at the end of the file, you don't need to "iterate" over it – simply open it in append mode:

with open("my_file", "a") as f:
    f.write("another line\n")

Iterating over files can be used to read them, not to write them.

like image 67
Sven Marnach Avatar answered Feb 06 '26 02:02

Sven Marnach