python如何向文件最开始插入一个字符串?
高洛峰
高洛峰 2017-04-18 09:03:04
0
5
397

在尽量保证性能的情况下

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回覆(5)
小葫芦

如果你要往已經存在的文件前面插入內容,那就不怎麼要考慮效能了。
因為無論如何你都要把這個檔案的內容重新讀寫一遍,這是檔案系統的邏輯決定的。

黄舟

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的檔案指標就在檔案開頭.

還有, 必須要遍歷文件內容的

PHPzhong

分兩點來探討這個問題:

  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.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 but none change the fundamental operation: You must read in the existing , thenfol wout the file. 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 codes that's notob​​ngrams programs of 代碼

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文件,把開頭的那些內容寫入一個新文件,再讀出原文件的內容,寫入新文件,然後把新文件重命名為原文件名稱。
雖然很暴力,後面發現,其實速度也很快,可能是文件不是太大的緣故。 ^_^

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板