How to modify a text file?


Question

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?

1
159
7/28/2017 7:12:05 PM

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.

131
10/9/2012 12:11:48 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon