我试图让python读取.txt文件的最后三行。我也试图将每一行添加为列表中的元素。
例如:
**list.txt**
line1
line2
line3
**python_program.py**
(read list.txt, insert items into line_list)
line_list[line1,line2,line3]
但是我对这个过程感到有点困惑。
非常感谢任何帮助!
答案 0 :(得分:5)
如果您正在处理一个非常大的文件怎么办?阅读内存中的所有行将是非常浪费的。另一种方法可能是:
from collections import deque
d=deque([], maxlen=3)
with open("file.txt") as f:
for l in f:
d.append(l)
这在给定时间内仅在读取的最后三行中保留在内存中(deque丢弃每个附加处的过多的最旧元素)。
正如@ user2357112指出的那样,这也会起作用,并且更具合成性:
from collections import deque
d=None
with open("file.txt") as f:
d=deque(f, maxlen=3)
答案 1 :(得分:1)
with open('list.txt') as f:
lines = f.readlines()
line_list = lines[-3:]
答案 2 :(得分:0)
试试这些:
#!/usr/local/cpython-3.3/bin/python
import pprint
def get_last_3_variant_1(file_):
# This is simple, but it also reads the entire file into memory
lines = file_.readlines()
return lines[-3:]
def get_last_3_variant_2(file_):
# This is more complex, but it only keeps three lines in memory at any given time
three_lines = []
for index, line in zip(range(3), file_):
three_lines.append(line)
for line in file_:
three_lines.append(line)
del three_lines[0]
return three_lines
get_last_3 = get_last_3_variant_2
def main():
# /etc/services is a long file
# /etc/adjtime is exactly 3 lines long on my system
# /etc/libao.conf is exactly 2 lines long on my system
for filename in ['/etc/services', '/etc/adjtime', '/etc/libao.conf']:
with open (filename, 'r') as file_:
result = get_last_3(file_)
pprint.pprint(result)
main()