How to modify a text file?

前端 未结 8 1386
不思量自难忘°
不思量自难忘° 2020-11-22 03:14

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?

8条回答
  •  感情败类
    2020-11-22 03:54

    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.

提交回复
热议问题