Python Forum

Full Version: Replace Line in Textfile
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a really simple query, but I can't find an answer to it. I'm new to Python and am learning for a project I'm setting up, but I seem to have fallen at the first hurdle.

All I want to do is replace a line in a text file. That's it. So, I've written the following:

f = open("test.txt", "rt")
data = f.read()
data = data.replace('python', 'Hello')
f.close()
f = open("test.txt", "wt")
f.write(data)
f.close()
which replaces the word 'python' with the word 'hello'. Easy.

But, how do I combine that with an If statement? Let's say the file only contains a single word: python. How do I get the system to check the single line in the file and, if it says 'python' replace it with the word 'hello', if it says anything else, print whatever the file contains?

It feels like it should be really simple, I just can't get there.
it's better to use a with statement, makes code easier to read, and closes files automatically:
import os
# assure in script directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))

def replace_a_line(original_line, new_line, filein, fileout):    
    with open(filein) as fin, open(fileout, 'w') as fout:
        for line in fin:
            lineout = line
            if line.strip() == original_line:
                lineout = f"{new_line}\n"
            fout.write(lineout)

def testit():
    replace_a_line('line 2', 'line xxx', 'testfilein.txt', 'testfileout.txt')

if __name__ == '__main__':
    testit()
testfilein.txt:
Output:
line 1 line 2 line 3
testfileout.txt
Output:
line 1 line xxx line 3