gopal gopal - 4 days ago 5
Python Question

How to update line of file in python

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

Answer

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')
Comments