簡體   English   中英

從文本文檔“蠶食”第一行文本然后在python中重新保存的最有效方法

[英]Most efficient way to “nibble” the first line of text from a text document then resave it in python

我有一個文本文檔,我想反復刪除每30秒左右的第一行文本。

我已經編寫(或更准確地復制)python resettable計時器對象的代碼,如果沒有要求重置或取消,它允許以非阻塞方式每30秒調用一次函數。

python中的可重置計時器重復,直到被取消

(如果有人可以檢查我實現重復的方式就可以了,因為我的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM