How to update existing line of file in Python?
Example: I want to update session.xml
to sesion-config.xml
without writing new line.
Input A.txt
:
fix-config = session.xml
Expected output A.txt
:
fix-config = session-config.xml
How to update existing line of file in Python?
Example: I want to update session.xml
to sesion-config.xml
without writing new line.
Input A.txt
:
fix-config = session.xml
Expected output A.txt
:
fix-config = session-config.xml
You can't mutate lines in a text file - you have to write an entirely new line, which, if not at the end of a file, requires rewriting all the rest.
The simplest way to do this is to store the file in a list, process it, and create a new file:
with open('A.txt') as f:
l = list(f)
with open('A.txt', 'w') as output:
for line in l:
if line.startswith('fix-config'):
output.write('fix-config = session-config.xml\n')
else:
output.write(line)
The solution @TigerhawkT3 suggested would work great for small/medium files. For extremely large files loading the entire file into memory might not be possible, and then you would want to process each line separately. Something along these lines should work:
import shutil
with open('A.txt') as input_file:
with open('temp.txt', 'w') as temp_file:
for l in input_file:
if l.startswith('fix-config'):
temp_file.write('fix-config = session-config.xml\n')
else:
temp_file.write(l)
shutil.move('temp.txt', 'A.txt')