将新数据写入文件的中间 [英] Write new data into the middle of a file
问题描述
写一个新文件很容易,附加到它等等。但是我怎样才能写入文件的中间?
我有一个由自动化过程生成的html报告,而不是重写整个报告,我只想将新数据插入到新的数据中。也许我想寻找一个评论,并附加在那里。所以,在<! - append here - >
如果文件太大,内存,逐行读写(或逐块,或任何适合)到一些临时文件,然后复制它,而不是原始文件。
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 report that is generated off of an automated process, and rather than rewrite the whole report, I want to just insert new data where it's new. Perhaps I want to look for a comment and append there. So, add new data after the line <!-- append here -->
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.
这篇关于将新数据写入文件的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!