Alex Rivera | Logout

How to modify a text file?

Asked 2008-09-24T06:30:56.650
237

I'm using Python, and would like to insert a string into a text file without deleting or copying the file. How can I do that?

Edit
Report

1 Answer

84

The fileinput module of the Python standard library will rewrite a file inplace if you use the inplace=1 parameter:

import sys
import fileinput

# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5th
for i, line in enumerate(fileinput.input('lorem_ipsum.txt', inplace=1)):
    sys.stdout.write(line.replace('sit', 'SIT'))  # replace 'sit' and write
    if i == 4: sys.stdout.write('\n')  # write a blank line after the 5th line
answered 2009-11-28T07:25:54.560

Your Answer