0

I have a .txt file in which I want to replace a specific line (line #3) with a string. I don't want to use a simple file.replace(targetString, newString) because I have multiple targetString in the file, and the orders in which they're in is unknown. I do know that the string I want to replace is always at the 3rd line, and it is the only thing on the 3rd line.

Currently my code looks something like this, I'm terrible at programming so I would appreciate the easiest answer you can think of

with open("LAB5INFO.txt", "r+") as file:
    content = file.read()
    file.seek(0)
    file.truncate()
    file.write(content.replace(<<LINE3>>, string))
2
  • Hi Oliver, I made a few changes to your question. I took the Python tag out of the title; as tags are discouraged. More significantly, I changed the spacing of your code block. Since this is python, the spacing change is significant. Please either edit the question or roll back my change if you find the change I made was not a true representation of the code you've written. Commented Sep 22, 2017 at 17:29
  • Also, if you're terrible at programming, why not just open the file in an editor and change that line? (If you want to change that line in a batch script, there are usually scripting alternatives that will do what you want.) Commented Sep 22, 2017 at 17:30

2 Answers 2

1

I guess?

with open("LAB5INFO.txt", "rb") as file:
    lines = file.readlines()
    lines[2].replace("old","new")
with open("LAB5INFO.txt", "wb") as file:
    file.write("\n".join(lines)
Sign up to request clarification or add additional context in comments.

Comments

0

borrowing from other answer, but here we don't need to know the content of the original line

with open("LAB5INFO.txt", "rb") as file:lines = file.readlines()
lines[2]="new third line"
with open("LAB5INFO.txt", "wb") as file: file.write("\n".join(lines))

Comments

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.