2

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
gopal
  • 35
  • 1
  • 5

2 Answers2

4

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)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • 1
    there is an exact duplicate of this question [here](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python). What do you think? – Ahsanul Haque Nov 29 '16 at 11:58
  • If you see a common question with a popular canonical duplicate, you can vote or flag the question for closure with that duplicate. – Jarvis Nov 29 '16 at 12:01
  • 1
    @Jarvis - Those are really familiar words. :P – TigerhawkT3 Nov 29 '16 at 12:02
2

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')
MatanRubin
  • 985
  • 8
  • 16