【问题标题】:Most efficient way to "nibble" the first line of text from a text document then resave it in python从文本文档中“蚕食”第一行文本然后在 python 中重新保存的最有效方法
【发布时间】:2013-03-27 11:09:00
【问题描述】:

我有一个文本文档,我想每隔 30 秒左右重复删除第一行文本。

我已经编写(或更准确地说是复制)python 可重置计时器对象的代码,该对象允许在不要求重置或取消的情况下以非阻塞方式每 30 秒调用一次函数。

Resettable timer in python repeats until cancelled

(如果有人可以检查我实现重复的方式没问题,因为我的 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)  

这可行,但这是最好的方法吗?

【问题讨论】:

    标签: python text-files deque


    【解决方案1】:

    我会将fileinput moduleinplace=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 异常。

    这使得重写 large 文件的效率更高,因为您只需将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)  
    

    但这需要你读取内存中的所有文件;不要对大文件这样做。

    【讨论】:

    • +1 for fileinput,您可能想评论标准输出如何重定向到文件
    猜你喜欢
    • 2016-05-16
    • 1970-01-01
    • 2016-05-09
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2010-10-06
    相关资源
    最近更新 更多