简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM