简体   繁体   English

在python中复制文本文件的最后三行?

[英]Copy the last three lines of a text file in python?

I'm new to python and the way it handles variables and arrays of variables in lists is quite alien to me. 我是python的新手,它处理变量和列表中变量数组的方式对我来说很陌生。 I would normally read a text file into a vector and then copy the last three into a new array/vector by determining the size of the vector and then looping with a for loop a copy function for the last size-three into a new array. 我通常会将一个文本文件读入一个向量,然后通过确定向量的大小将最后三个文件复制到一个新的数组/向量中,然后使用for循环将最后一个size-3的复制函数循环到一个新数组中。

I don't understand how for loops work in python so I can't do that. 我不明白循环如何在python中工作所以我不能这样做。

so far I have: 到目前为止我有:

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

To get the last three lines of a file efficiently, use deque : 要有效地获取文件的最后三行,请使用deque

from collections import deque

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

This saves reading the whole file into memory to slice off what you didn't actually want. 这样可以将整个文件读入内存,以切断您实际不想要的内容。

To reflect your comment - your complete code would be: 要反映您的评论 - 您的完整代码将是:

from collections import deque

with open('somefile') as fin, open('outputfile', 'w') as fout:
    fout.writelines(deque(fin, 3))

As long as you're ok to hold all of the file lines in memory, you can slice the list of lines to get the last x items. 只要您可以将所有文件行保存在内存中,就可以对行列表进行切片以获取最后的x项。 See http://docs.python.org/2/tutorial/introduction.html and search for 'slice notation'. 请参阅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']

First to answer your question, my guress is that you had an index error you should replace the line writeLine[i] with writeLine.append( ). 首先回答你的问题,我的意思是你有一个索引错误,你应该用writeLine.append()替换writeLine [i]行。 After that, you should also do a loop to write the output : 之后,您还应该执行循环来编写输出:

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

May I suggest a more pythonic way to write this ? 我可以建议用更pythonic的方式来写这个吗? It would be as follow : 它将如下:

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)

A possible solution: 可能的解决方案:

lines = [ l for l in open("Output.txt")]
file = open('Output.txt', 'w')
file.write(lines[-3:0])
file.close()

This might be a little clearer if you do not know python syntax. 如果您不了解python语法,这可能会更清楚一些。

lst_lines = lines.split() lst_lines = lines.split()

This will create a list containing all the lines in the text file. 这将创建一个包含文本文件中所有行的列表。

Then for the last line you can do: 然后你可以做最后一行:

last = lst_lines[-1] secondLAst = lst_lines[-2] etc... list and string indexes can be reached from the end with the '-'. last = lst_lines [-1] secondLAst = lst_lines [-2] etc ...列表和字符串索引可以从末尾到达' - '。

or you can loop through them and print specific ones using: 或者你可以使用以下方法遍历它们并打印特定的:

start = start line, stop = where to end, step = what to increment by. start = start line,stop = where to end,step =要递增的内容。

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

then just write them to a file. 然后将它们写入文件。

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

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