Python makes a lot of things easy and contains libraries and wrappers for a lot of common operations, but the goal is not to hide fundamental truths.
The fundamental truth you are encountering here is that you generally can't prepend data to an existing flat structure without rewriting the entire structure. This is true regardless of language.
There are ways to save a filehandle or make your code less readable, many of which are provided in other answers, but none change the fundamental operation: You must read in the existing file, then write out the data you want to prepend, followed by the existing data you read in.
By all means save yourself the filehandle, but don't go looking to pack this operation into as few lines of code as possible. In fact, never go looking for the fewest lines of code -- that's obfuscation, not programming.
如果你要往已经存在的文件前面插入内容,那就不怎么要考虑性能了。
因为无论如何你都要把这个文件的内容重新读写一遍,这是文件系统的逻辑决定的。
file.seek(0) 这个是offset 设定成0 也就 最开始部分。
可以用file.tell() 来确认。
可以参照一下两个网页。
https://docs.python.org/2/tutorial/inputoutput.html
http://www.tutorialspoint.com/python/file_seek.htm
不需要seek(0)
r+
model的文件指针就在文件开头.还有, 必须要遍历文件内容的
分两点来探讨这个问题:
如何有效率的来插入内容到档案的头或中间,有效率指的是较少的时间(较快的速度)与资源利用.
如何能够写出足够 pythonic 的 code 来处理这件事
我先说我的结论(如果有任何其他看法欢迎讨论,也许我是错的):
做不到
只要不是写得太糟或太难阅读,我觉得平庸一点或是较长的 code 也无妨(甚至更好)
引大神的话来佐证一下:
参考资料:
Prepend a line to an existing file in Python
我回答过的问题: Python-QA
没有办法在开头直接插入内容,必需读一遍文件。
这个问题我以前也想过,当时是反编译了一个python项目,需要批量处理所有文件,在每个python文件开头插入以下内容:
也尝试过很多方法,当时也网上到处找方法,终究无果。
所以,最后还是用了最简单暴力的方法,用
osd.walk
遍历所有python文件,把开头的那些内容写入一个新文件,再读出原文件的内容,写入新文件,然后把新文件重命名为原文件名称。虽然很暴力,后面发现,其实速度也很快,可能是文件不是太大的缘故。^_^