Nov-04-2019, 07:14 PM
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.txtOutput:line 1
line xxx
line 3