![](/img/trans.png)
[英]How would I go about printing a line that reads “ input errors detected” based on the output of the sent command?
[英]How would I go about printing the last line in a large text file?
我将如何打印文本文件中的最后一行,该文本文件约为612 MB
,包含约400万行文本,其中包括This is a line
。 到目前为止,我有:
File.py
f = open("foo.txt","r+")
datalist = []
for line in f:
datalist.append(line)
print(datalist[-1])
我在代码中看到的唯一问题是它占用了大量内存。 我听说有人使用os.lseek
代替,但是我不知道如何实现它。
如果只需要最后一行,则将其他所有内容都丢弃。
with open('foo.txt') as f:
for line in f:
pass
# `line` is the last line of the file.
从文件的末尾开始,然后向后移字节,直到找到\\n
,然后读取,这会更快(但可读性差得多)。
with open('foo.txt') as f:
fd = f.fileno()
os.lseek(fd, 0, os.SEEK_END)
while True:
ch = os.read(fd, 1)
if ch == b'\n':
line = f.read()
break
else:
os.lseek(fd, -2, os.SEEK_CUR)
# `line` is the last line of the file
这是通过从头开始读取文件,寻找第一个换行符,然后从那里向前读取来实现的。
这是一个非常简单的改进,一次只能存储一行:
f = open("foo.txt","r")
data = None
for line in f:
data = line
print(data)
或者,您可以在循环后获取最终的循环值:
f = open("foo.txt","r")
line = None
for line in f:
pass
print(line)
请注意,在此示例中,如果文件为空,则line
将为None
(这是对line
进行初始分配的原因)。
一个快速的改进就是只丢弃datalist
,只保存最新的行,因为这就是您关心的全部。
f = open("foo.txt","r+")
for line in f:
pass
print(line)
我以为还有其他更有效的方法。 我只想提供一个直接衍生您代码的代码。
您无需将每一行添加到列表中。 只需使用循环变量:
line = None # prevents a NameError if the file is empty
with open("foo.txt", "r+") as f:
for line in f:
pass
print(line)
在回收模块中检查双端队列 。 有一种方法可以查看文件中的最后n行。 即尾巴。
https://docs.python.org/2/library/collections.html#deque-recipes
def tail(filename, n=10):
'Return the last n lines of a file'
return deque(open(filename), n)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.