How to modify a text file? How to modify a text file? python python

How to modify a text file?


Unfortunately there is no way to insert into the middle of a file without re-writing it. As previous posters have indicated, you can append to a file or overwrite part of it using seek but if you want to add stuff at the beginning or the middle, you'll have to rewrite it.

This is an operating system thing, not a Python thing. It is the same in all languages.

What I usually do is read from the file, make the modifications and write it out to a new file called myfile.txt.tmp or something like that. This is better than reading the whole file into memory because the file may be too large for that. Once the temporary file is completed, I rename it the same as the original file.

This is a good, safe way to do it because if the file write crashes or aborts for any reason, you still have your untouched original file.


Depends on what you want to do. To append you can open it with "a":

 with open("foo.txt", "a") as f:     f.write("new line\n")

If you want to preprend something you have to read from the file first:

with open("foo.txt", "r+") as f:     old = f.read() # read everything in the file     f.seek(0) # rewind     f.write("new line\n" + old) # write the new line before


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

import sysimport fileinput# replace all occurrences of 'sit' with 'SIT' and insert a line after the 5thfor 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