首页 > python如何向文件最开始插入一个字符串?

python如何向文件最开始插入一个字符串?

在尽量保证性能的情况下


如果你要往已经存在的文件前面插入内容,那就不怎么要考虑性能了。
因为无论如何你都要把这个文件的内容重新读写一遍,这是文件系统的逻辑决定的。


不需要seek(0)

r+ model的文件指针就在文件开头.

还有, 必须要遍历文件内容的


分兩點來探討這個問題:

  1. 如何有效率的來插入內容到檔案的頭或中間,有效率指的是較少的時間(較快的速度)與資源利用.

  2. 如何能夠寫出足夠 pythonic 的 code 來處理這件事

我先說我的結論(如果有任何其他看法歡迎討論,也許我是錯的):

  1. 做不到

  2. 只要不是寫得太糟或太難閱讀,我覺得平庸一點或是較長的 code 也無妨(甚至更好)

引大神的話來佐證一下:

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.

By Nicholas Knight

參考資料:

Prepend a line to an existing file in Python


我回答過的問題: Python-QA


没有办法在开头直接插入内容,必需读一遍文件。
这个问题我以前也想过,当时是反编译了一个python项目,需要批量处理所有文件,在每个python文件开头插入以下内容:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

也尝试过很多方法,当时也网上到处找方法,终究无果。
所以,最后还是用了最简单暴力的方法,用osd.walk遍历所有python文件,把开头的那些内容写入一个新文件,再读出原文件的内容,写入新文件,然后把新文件重命名为原文件名称。
虽然很暴力,后面发现,其实速度也很快,可能是文件不是太大的缘故。^_^


file.seek(0) 这个是offset 设定成0 也就 最开始部分。
可以用file.tell() 来确认。
可以参照一下两个网页。
https://docs.python.org/2/tutorial/inputoutput.html
http://www.tutorialspoint.com/python/file_seek.htm

【热门文章】
【热门文章】