Appending A Specific Line After Having Found It In Python
I am writing a function that allows a user to look for content in a specific line (in a file), and replace part of that content in that line, and re-writes it to the file on the sa
Solution 1:
The way you need to do this, and the way most programs do it - is to write a temporary file with the correct output, then replace the original file. This is the most fool proof way.
Here is the general logic:
- Open the input file, and a temporary output file.
- Read a line from the input file:
- If it matches the replacement criteria, write the new modified line to the temporary output file; otherwise write the line to the output file as-is.
- Once all lines have been processes, close the input file.
- Delete the input file.
- Rename the temporary file with the same name as the input file.
To implement it in Python:
import os
with open('input.txt') as i, open('output.txt', 'w') as o:
for line in i:
if line.startswith('Replace Me:'):
line = 'New line, replaced the old line.\n'
o.write(line)
os.rename('output.txt', 'input.txt')
Post a Comment for "Appending A Specific Line After Having Found It In Python"