5

我是 python 新手,它处理列表中变量和变量数组的方式对我来说很陌生。我通常会将一个文本文件读入一个向量,然后通过确定向量的大小将最后三个复制到一个新的数组/向量中,然后使用 for 循环将最后一个大小为三个的复制函数复制到一个新数组中。

我不明白 for 循环在 python 中是如何工作的,所以我不能这样做。

到目前为止,我有:

    #read text file into line list
            numberOfLinesInChat = 3
    text_file = open("Output.txt", "r")
    lines = text_file.readlines()
    text_file.close()
    writeLines = []
    if len(lines) > numberOfLinesInChat:
                    i = 0
        while ((numberOfLinesInChat-i) >= 0):
            writeLine[i] = lines[(len(lines)-(numberOfLinesInChat-i))]
                            i+= 1

    #write what people say to text file
    text_file = open("Output.txt", "w")
    text_file.write(writeLines)
    text_file.close()
4

5 回答 5

12

要有效地获取文件的最后三行,请使用deque

from collections import deque

with open('somefile') as fin:
    last3 = deque(fin, 3)

这样可以节省将整个文件读入内存以切掉您实际上不想要的内容。

为了反映您的评论 - 您的完整代码将是:

from collections import deque

with open('somefile') as fin, open('outputfile', 'w') as fout:
    fout.writelines(deque(fin, 3))
于 2013-03-26T21:33:21.550 回答
3

只要您可以将所有文件行保存在内存中,就可以对行列表进行切片以获取最后 x 项。请参阅http://docs.python.org/2/tutorial/introduction.html并搜索“切片表示法”。

def get_chat_lines(file_path, num_chat_lines):
    with open(file_path) as src:
        lines = src.readlines()
        return lines[-num_chat_lines:]


>>> lines = get_chat_lines('Output.txt', 3)
>>> print(lines)
... ['line n-3\n', 'line n-2\n', 'line n-1']
于 2013-03-26T21:19:02.610 回答
0

首先回答你的问题,我猜你有一个索引错误,你应该用 writeLine.append() 替换行 writeLine[i]。之后,您还应该执行一个循环来编写输出:

text_file = open("Output.txt", "w")
for row in writeLine :
    text_file.write(row)
text_file.close()

我可以建议一种更pythonic的方式来写这个吗?如下:

with open("Input.txt") as f_in, open("Output.txt", "w") as f_out :
    for row in f_in.readlines()[-3:] :
        f_out.write(row)
于 2013-03-26T21:15:58.933 回答
0

一个可能的解决方案:

lines = [ l for l in open("Output.txt")]
file = open('Output.txt', 'w')
file.write(lines[-3:0])
file.close()
于 2013-03-26T21:30:22.563 回答
0

如果您不了解 python 语法,这可能会更清楚一些。

lst_lines = lines.split()

这将创建一个包含文本文件中所有行的列表。

然后对于最后一行,您可以执行以下操作:

last = lst_lines[-1] secondLAst = lst_lines[-2] 等...列表和字符串索引可以从末尾使用“-”到达。

或者您可以遍历它们并使用以下方法打印特定的:

start = 起始行,stop = 结束位置,step = 递增的内容。

for i in range(start, stop-1, step): string = lst_lines[i]

然后只需将它们写入文件即可。

于 2013-03-26T22:27:14.160 回答