最有效的方法是“啃”文本文档的第一行文本,然后将其重新保存在python中

2024-09-21 01:14:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我已经为python resetable timer对象编写了(或者更准确地复制了)代码,该对象允许在不要求重置或取消的情况下每隔30秒以非阻塞方式调用一个函数。你知道吗

Resettable timer in python repeats until cancelled

(如果有人能检查一下我在中实现repeat的方式,那就没问题了,因为我的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)  

这很管用,但这是最好的方法吗?你知道吗


Tags: path对象函数文本aswith方式文本文档
1条回答
网友
1楼 · 发布于 2024-09-21 01:14:47

我会用^{} 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异常。你知道吗

这使得重写大的文件更加有效,因为您只需要将fileinputreadlines缓冲区保留在内存中。你知道吗

我认为根本不需要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)  

但这需要您读取内存中的所有文件;不要对大文件执行此操作。你知道吗

相关问题 更多 >

    热门问题