0

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?

1 Answer 1

1

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.

P.S.- 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.

Sign up to request clarification or add additional context in comments.

2 Comments

What you suggested works perfectly - thanks alot!
Good to hear that. Have fun coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.