0

Now, I know this kind of question has been kind asked before, but this is slightly different.
I want to use a file main.py to remove MULTIPLE lines from another file targetfile.py
These multiple lines are all together, like:

line_To_Delete1
line_To_Delete2
line_To_Delete3
line_To_Replace1  

All these lines will have the comments #del1 , #del2 or something that indentifies it as unique, and the one to delete/replace.
So how do I delete all these lines together?
Also, I want to replace the 4th line with some other line.
How do I do all this?

2
  • How do you know which lines to delete? Commented Sep 8, 2020 at 0:23
  • @Mike67 I have added more details to the question Commented Sep 8, 2020 at 6:25

1 Answer 1

1

To remove lines from a file based on a condition, you can just read the lines from the one file then write them to another if the condition is false.

Try this code:

txt = '''
print(1)
print(2)
print(3)  #del1
print(4)  #del2
print(5)  #rep1
print(6)
print(7)
'''.strip()

with open("targetfile.py",'w') as f:  # write test file
    f.write(txt)

######### main script #########

repstr = "NewText"

outstr = ""
with open("targetfile.py") as f1:
   for ln in f1.readlines():
      if "#rep" in ln:    # condition to replace line
          outstr += repstr + '\n'
      elif not "#del" in ln:  # condition to copy line
          outstr += ln
             
with open("targetfile.py",'w') as f2:  # overwrite file
    f2.write(outstr)

Output (targetfile.py)

print(1)
print(2)
NewText
print(6)
print(7)
Sign up to request clarification or add additional context in comments.

4 Comments

How do I do it without creating a new file? And how do I replace specific lines?
Great answer. Just one last question. If I already have a text file that is in ANOTHER directory, and I enter the path in open(), will it still work?
yes - something like open('c:/tmp/myfile.py') should work fine.
I know I could get into trouble for writing this, but Thank You so Much. Man, this was so very important to me, and you made my day with this solution. Anyone can delete this comment or downvote my question, but it'll be worth it. Thank You so much.

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.