在python中复制文本文件的最后三行? [英] Copy the last three lines of a text file in python?

查看:259
本文介绍了在python中复制文本文件的最后三行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to python and the way it handles variables and arrays of variables in lists is quite alien to me. 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循环如何在python中工作,所以我无法做到这一点.

I don't understand how for loops work in python so I can't do that.

到目前为止,我有:

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

推荐答案

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

To get the last three lines of a file efficiently, use 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))

这篇关于在python中复制文本文件的最后三行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆