Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
76 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 Reply

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)
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...