我正在製作一個腳本,用於檢查/創建/更新項目中源文件頂部的版權聲明。將(生成的)標題添加到多個文件的最有效方法?
這通常是I/O限制,因爲每次使用腳本時,標題(缺失或其他)都會變得更大(例如,爲現有通知添加更多年),因此文件的其餘部分必須是重新定位到稍後的偏移量。這意味着讀取整個文件,然後寫回(+我想要的小標題更改)。
它發生在我身上,有可能是一個更有效的方法來做到這一點。這個用例並不罕見嗎?
我天真地以爲有可能尋求到一個負的,你可以尋求過去的文件(這通常會導致稀疏文件)結束以同樣的方式抵消。
import os
fh = file("code.py", "rb+")
original_size = os.fstat(fh.fileno()).st_size
data = fh.read()
# `prefix` should be prepended to the file
# `updated_data` is anchored to offset 0, and likely only a
# few 10s of bytes long (unlike the original file)
# `suffix should` be postpended to the file
prefix, updated_data, suffix = get_changes(data)
fh.seek(0)
fh.write(updated_data)
# WISHFUL THINKING. Not possible to seek to a negative offset.
fh.seek(-1 * len(prefix))
fh.write(prefix)
fh.seek(max(original_size, len(updated_data)))
fh.write(suffix)
fh.close()
環境的東西:
- 的Python V2.6
- 的GNU/Linux(Red Hat企業5 + Ubuntu的10.04,如果它事項)
尋求替代回回,你爲什麼不能寫前綴第一,其次是updated_data其次後綴? – Abhijit
沒理由,我只想說明我的數據是如何構建的。在生產代碼中,我會避免不必要的尋求,因爲你建議。 – RobM