python - 最有效的方法是从文本文档中获取 "nibble"第一行文本,然后将其重新保存在 python 中

标签 python text-files deque

我有一个文本文档,我想每隔 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)  

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

最佳答案

我会使用 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 异常。

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

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

关于python - 最有效的方法是从文本文档中获取 "nibble"第一行文本,然后将其重新保存在 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657380/

相关文章:

rust - 如何更新 VecDeque 中的值?

python - pyspark : Convert DataFrame to RDD[string]

powershell - 如何从文本文件中提取特定行

iphone - 在 iPhone 应用程序开发中,如何将数据存储到文本文件中并在应用程序再次启动时检索它?

C语言——使用文件IO、结构体、函数、数组、指针在文本文件中记录数据(添加、删除)

java - 队列未清除已消费的消息

python - OpenCV 3.0缺少诸如drawMatches和drawMatchesKNN的方法

python - 动态创建一个派生自 ABC 类的类

python - 我可以向 Scikit learn Pipeline 添加异常值检测和删除吗?

java - 无法解决 Java 双端队列迭代错误