从文件底部删除部分文本文件

时间:2018-06-05 08:20:04

标签: python-3.x file edit

我有一个如下文本文件:

text1
text2
17
28
34
text1
text2
77
66
55
text1
text2
34
12
42
1

我想从文本文件的底部找到第一个“text1”并将其从原始文件中删除。它应该给我这个结果:

text1
text2
17
28
34
text1
text2
77
66
55

如何从底部读取文件?是否有可能或我应该找到另一种方式?

1 个答案:

答案 0 :(得分:1)

这是一种方法。

<强>演示:

checkText = "text1"
sliceVal = 0
with open(filename, "r") as infile:      
    data = infile.readlines()                  #Read line in your text
    for i, v in enumerate(reversed(data)):     #Reverse the lines 
        if v.strip() == checkText:             #Check for word
            sliceVal = i                       #Store line number                      
            break
if sliceVal:
    data = list(reversed(data))
    data = reversed(data[sliceVal+1:])         #Strip the data
    with open(filename, "w") as outfile:       #Write back new data to file.
        for i in data:
            outfile.write(i)
else:
    print( "Check Word Not Found" )