【问题标题】:Copy the last three lines of a text file in python?在python中复制文本文件的最后三行?
【发布时间】:2013-03-26 21:09:19
【问题描述】:

我是 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()

【问题讨论】:

  • print >> my_file,"\n".join(lines[-3:])
  • Joran 的评论仅适用于 Python 3 之前的版本。

标签: python list text


【解决方案1】:

要有效获取文件的最后三行,请使用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))

【讨论】:

  • 哇!我不知道这个技巧。它在内部是如何工作的?读者是否逐行阅读并只保留最后三行?我的意思是我会以更详细的模式编写:lines = [] for row in lines:lines.append(row) lines = lines[-3:]
  • 这看起来不错,如果文件包含少于 3 行,它会工作吗?
  • @Zac 如果没有 3 行 - 你会得到剩余的
  • @MrDave collections.deque 可以是一个 ummm,“双端队列”——它还有一个可以放入对象空间的最大尺寸,以便最早从队列中删除一个新条目。 ..所以喂了一个迭代器它就是这样做的......
  • 当我将 last3 写入文件时,我必须使用 str(last3) 否则会出现字符串缓冲区错误,但如果这样做,我会收到大量额外的 deque 和 max len 字符?如何从 last3 中写入 /n 终止的字符串?
【解决方案2】:

只要您可以将所有文件行保存在内存中,您就可以对行列表进行切片以获取最后 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']

【讨论】:

    【解决方案3】:

    首先回答你的问题,我猜你有一个索引错误,你应该用 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)
    

    【讨论】:

    • 所以更pythonic的方式是......什么都没有?
    • 哈哈。我正在努力为代码提供一个很好的缩进。
    • 还有一点:如果少于三行,则没有pb,代码将只写需要的行。
    • 我看不懂那个底部的例子。我想阅读底部的三行,然后用附加的附加行将它们重新写入同一个文件,我不确定 input.txt 会出现在哪里。为了给你一些问题的背景,额外的行由 IRC 聊天提供,我基本上想要一个文本文件,更新后仅包含 IRC 聊天的最后 4 行。
    • 抱歉,请将 Input.txt 替换为 somefile。 with ... 强制在 blocl 的出口处,这两个文件将被关闭。 f_in.readlines() 返回从 somefile 读取的所有行,截断为最后三个 [-3:]。最后,结果列表上的循环正在写入输出文件中的每一行。
    【解决方案4】:

    一个可能的解决方案:

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

    【讨论】:

      【解决方案5】:

      如果你不懂python语法,这可能会更清楚一点。

      lst_lines = lines.split()

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

      那么最后一行你可以做:

      最后一个 = lst_lines[-1] secondLAst = lst_lines[-2] 等等...列表和字符串索引可以从末尾用'-'到达。

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

      start = 起始行,stop = 结束位置,step = 增量。

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

      然后将它们写入文件。

      【讨论】:

        猜你喜欢
        • 2017-12-25
        • 2016-03-20
        • 1970-01-01
        • 1970-01-01
        • 2015-03-05
        • 2017-08-27
        • 2016-05-09
        • 2021-11-22
        • 1970-01-01
        相关资源
        最近更新 更多