2

I want to replace a line in a text file using Python. Basically I am looping over a file and when I find a relevant line that needs to be replaced, I want to replace it at the same position in the file.

Can this be done in Python without creating a completely new file?

Alois Mahdal
  • 10,763
  • 7
  • 51
  • 69
Saurabh
  • 25
  • 2
  • 4

1 Answers1

3

I like using the fileinput module for this. It has an option for making a backup file, and it preserves permissions.

import fileinput
import sys

for line in fileinput.input([filename], inplace=True):
    if condition:
        sys.stdout.write(newline)
    else:
        sys.stdout.write(line)

This does create a new (temporary) file, then renames that file to filename, so the change appears to be in-place.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677