简体   繁体   中英

Python: Remove first instance only of string from text file

I have been removing the desired lines from a text file by reading it in and rewriting each line if the string(s) I wish to remove are not present, using the following.

with open('infile.txt', 'r') as f:
    lines = f.readlines()
with open('outfile.txt', 'w+') as f:
    for line in lines:
        if line.strip("\n") != "Desired text on line to remove":
            f.write(line)

This works fine for all but one of the lines I need to remove which only contains.

1.

This is the first instance of (1.) in the file, and always will be in the files I'm editing; however it is repeated later in the text file and these later instances must be kept - is it possible to remove only the first instance of this text?

First of all, in the code you mentioned f.readlines() should be lines which you mistakenly typed as line so please edit the question.

Now coming to the question. If I've understood your question correctly then you want to get rid of first '1.' and keep the rest. It can be done in multiple ways, like below code.

with open('infile.txt', 'r') as f:
    lines = f.readlines()
with open('outfile.txt', 'w+') as f:
    t = '1.'
    for line in lines:
        line = line.strip("\n")
        if line != "Desired text on line to remove" and line != t:
            f.write(line)
            f.write("\n")
        if line == t:
            t = None
          

One of them is by simply using logical operators (which I've used) and create a variable you want to remove. Which in my case as t . Now use it to filter the first instance. Thereafter change its value to None so that in the next instance it will always be a True statement and the condition to run or not depends on if line is equal to our desired text or not.

PS- I've added some more line of codes like line = line.strip("\n") and f.write("\n") just to make the output and code clearer. You can remove it if you want as they don't contribute to clear the hurdle.

Moreover, if you don't get the desired output or my code is wrong. Feel free to point it out as I've not written any answers yet and still learning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM