简体   繁体   English

Python如何读取.txt文件的最后三行,并将这些项目放入列表中?

[英]Python how to read last three lines of a .txt file, and put those items into a list?

I am trying to have python read the last three lines of a .txt file. 我正在尝试让python读取.txt文件的最后三行。 I am also trying to add each line as an element in a list. 我也试图将每一行添加为列表中的元素。

So for instance: 因此,例如:

**list.txt**
line1
line2
line3

**python_program.py**
(read list.txt, insert items into line_list)
line_list[line1,line2,line3]

However I am a bit confused on this process. 但是我对此过程有些困惑。

Any help would be greatly appreciated! 任何帮助将不胜感激!

What if you are dealing with a very big file? 如果您要处理的文件很大怎么办? Reading all the lines in memory is going to be quite wasteful. 读取内存中的所有行将非常浪费。 An alternative approach may be: 一种替代方法可能是:

from collections import deque 
d=deque([], maxlen=3)
with open("file.txt") as f:
    for l in f:
       d.append(l) 

This keeps in memory at a given time only the last three rows read (the deque discards the oldest elements in excess at each append). 在给定的时间,这仅将最后三行读入内存(双端队列在每次追加时都丢弃多余的最旧元素)。


As @user2357112 points out, this will work as well, and is more synthetic: 正如@ user2357112指出的那样,这也可以正常工作,并且更加综合:

from collections import deque 
d=None
with open("file.txt") as f:
    d=deque(f, maxlen=3)
with open('list.txt') as f:
    lines = f.readlines()
line_list = lines[-3:]

Try these: 试试这些:

#!/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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM