removing a part of text file from bottom of the file

I have a text file like following:

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

I want to find the first "text1" from the bottom of the text-file and remove it from original file. and it shoul give me this result:

text1
text2
17
28
34
text1
text2
77
66
55

How can I read a file from bottom? Is it possible or I should find another way?

Upvotes: 1

Views: 31

Answers (1)

Rakesh
Rakesh

Reputation: 82785

This is one approach.

Demo:

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

Upvotes: 1

Related Questions