Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
79 views
in Technique[技术] by (71.8m points)

python - delete all rows up to a specific row

How you can implement deleting lines in a text document up to a certain line? I find the line number using the code:

#!/usr/bin/env python
lookup = '00:00:00'
filename = "test.txt"
with open(filename) as text_file:
    for num, line in enumerate(text_file, 1):
        if lookup in line:
            print(num)

print(num) outputs me the value of the string, for example 66. How do I delete all the lines up to 66, i.e. up to the found line by word?

question from:https://stackoverflow.com/questions/65885950/delete-all-rows-up-to-a-specific-row

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's easy.

filename = "test.txt"
lookup = '00:00:00'
with open(filename,'r') as text_file:
    lines = text_file.readlines()
res=[]
for i in range(0,len(lines),1):
    if lookup in lines[i]:
        res=lines[i:]
        break
with open(filename,'w') as text_file:
    text_file.writelines(res)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...