从文件底部删除一部分文本文件
removing a part of text file from bottom of the file
我有一个如下所示的文本文件:
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
如何从底部读取文件?有可能还是我应该另辟蹊径?
这是一种方法。
演示:
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" )
我有一个如下所示的文本文件:
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
如何从底部读取文件?有可能还是我应该另辟蹊径?
这是一种方法。
演示:
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" )