user1581399
user1581399

Reputation: 31

start iteration from a specific line in a text file in 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?

Upvotes: 3

Views: 183

Answers (2)

Inbar Rose
Inbar Rose

Reputation: 43447

when you "open" the file, using the conventional

f = open(FILE) 

you should state the method of you are using, in this case, append, so

f = open(FILE, 'a')

Upvotes: 0

Sven Marnach
Sven Marnach

Reputation: 601669

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.

Upvotes: 6

Related Questions