我有一个文本文档,我想每隔 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
module与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)
但这需要你读取内存中的所有文件;不要对大文件这样做。
关于python - 最有效的方法是从文本文档中获取 "nibble"第一行文本,然后将其重新保存在 python 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15657380/