![](/img/trans.png)
[英]What is the most efficient way to get first and last line of a text file?
[英]Most efficient way to “nibble” the first line of text from a text document then resave it in python
我有一個文本文檔,我想反復刪除每30秒左右的第一行文本。
我已經編寫(或更准確地復制)python resettable計時器對象的代碼,如果沒有要求重置或取消,它允許以非阻塞方式每30秒調用一次函數。
(如果有人可以檢查我實現重復的方式就可以了,因為我的python有時會在運行時崩潰,不勝感激:))
我現在想編寫我的函數來加載文本文件,並且可能復制除第一行之外的所有文件,然后將其重寫為同一文本文件。 我這樣做可以做到這一點,我認為......但它是最有效的嗎?
def removeLine():
with open(path, 'rU') as file:
lines = deque(file)
try:
print lines.popleft()
except IndexError:
print "Nothing to pop?"
with open(path, 'w') as file:
file.writelines(lines)
這有效,但這是最好的方法嗎?
我將fileinput
模塊與fileinput
inplace=True
:
import fileinput
def removeLine():
inputfile = fileinput.input(path, inplace=True, mode='rU')
next(inputfile, None) # skip a line *if present*
for line in inputfile:
print line, # write out again, but without an extra newline
inputfile.close()
inplace=True
導致sys.stdout
被重定向到打開的文件,因此我們可以簡單地“打印”這些行。
next()
調用用於跳過第一行; 給它一個默認值None
禁止空文件的StopIteration
異常。
這使得重寫大文件更有效,因為您只需要將fileinput
readlines緩沖區保留在內存中。
我認為根本不需要deque
,即使是你的解決方案; 只是在那里使用next()
,然后使用list()
來捕獲剩余的行:
def removeLine():
with open(path, 'rU') as file:
next(file, None) # skip a line *if present*
lines = list(file)
with open(path, 'w') as file:
file.writelines(lines)
但這需要你讀取內存中的所有文件; 不要對大文件這樣做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.