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
2

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

3 Comments

there is an exact duplicate of this question here. What do you think?
If you see a common question with a popular canonical duplicate, you can vote or flag the question for closure with that duplicate.
@Jarvis - Those are really familiar words. :P
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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.