Agatha S
Agatha S

Reputation: 23

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.

Upvotes: 0

Views: 521

Answers (2)

AKX
AKX

Reputation: 169051

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)

– i.e. 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.

Upvotes: 1

Diogo
Diogo

Reputation: 101

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

Upvotes: 1

Related Questions