简体   繁体   中英

Delete all lines in file until line with string

I'm writting a script for editing a file.txt. I have a string name:

str_name = 'abcd'

My file has a lot of lines. I delete all the lines before str_name , and left in the file line with str_name and all below.

file = open(local_filename, "r")
lines = file.readlines()
for line in lines:
    if str_name in line:
        print("Find")
        start = lines.index(line)
        lines = lines[start::1]
        break
    else:
        print("Not found")
file.close()
file = open(local_filename, "wt")
for line in lines:
    file.write(f"{line}")
file.close()

To avoid reading all of the file into memory, you can do

with open(local_filename, "r") as f, open(local_filename + ".new", "w") as outf:
    found = False
    for line in f:
        if str_name in line:
            found = True
        if found:
            outf.write(line)

– ie keep track whether you've found the line you need, and if you have, begin writing them into another file.

If you want, you can do an os.rename() at the end to replace the new file into place.

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