Write New Data Into The Middle Of A File
Possible Duplicate: How do I modify a text file in Python? It's easy to write a new file, append to it, etc. But how can I write to the middle of a file? I have an html repo
Solution 1:
Yes.
- Read the file in
- Modify what you need
- Overwrite the file with the modified version
If the file is too big to fit into memory, read and write it line by line (or block by block, or whatever fits) into some temporary file, and then copy it instead of the original file.
Solution 2:
Solution 3:
If your edit would change the size of the file, then you will need to rewrite everything after the edit (as Eli suggests). If you have a large amount of blank space somewhere in the file, then you should be able to just re-write new data into that blank space without affecting the later parts of the file (and you would use file.seek() for this, as Max suggests).
So your idea (leaving a comment telling the program where to insert data) should work as long as the comment is followed by enough blank space to contain any new data you might put there.
Post a Comment for "Write New Data Into The Middle Of A File"