【问题标题】:How to write lines from a input file to an output file in reversed order in python 3如何在python 3中以相反的顺序将输入文件中的行写入输出文件
【发布时间】:2013-04-18 22:31:30
【问题描述】:

我想做的是从一个文本文档中取出一系列行,然后在一秒钟内将它们反转。例如文本文档 a 包含:

hi
there
people

因此,我想将这些相同的行写入文本文档 b,除了这样:

people
there
hi

到目前为止我有:

def write_matching_lines(input_filename, output_filename):
    infile = open(input_filename)
    lines = infile.readlines()
    outfile = open(output_filename, 'w')
    for line in reversed(lines):
            outfile.write(line.rstrip())
    infile.close()
    outfile.close()

但这只会返回:

peopletherehi 

在一行中。任何帮助将不胜感激。

【问题讨论】:

  • 写入文件时连接新行:outfile.write(line.rstrip() + '\r')
  • 哦,哇,我怎么错过了……非常感谢!

标签: python python-3.x readlines


【解决方案1】:

一行就可以了:

open("out", "wb").writelines(reversed(open("in").readlines()))

【讨论】:

    【解决方案2】:

    您只需要+ '\n',因为.write 不会为您这样做,或者您可以使用

    print >>f, line.rstrip()
    

    在 Python 3 中等效:

    print(line.rstrip(), file=f) 
    

    这将为您添加一个新行。或者做这样的事情:

    >>> with open('text.txt') as fin, open('out.txt', 'w') as fout:
            fout.writelines(reversed([line.rstrip() + '\n' for line in fin]))
    

    这段代码假设你不知道最后一行是否有换行符,如果你知道你可以使用

    fout.writelines(reversed(fin.readlines()))
    

    【讨论】:

      【解决方案3】:

      为什么在写之前你 rstrip() 你的行?在编写时,您将在每行末尾剥离换行符。然后你注意到你没有任何换行符。只需删除您写入的 rstrip()。

      少即是多。

      更新

      如果我不能证明/验证最后一行有一个终止换行符,我个人倾向于在前面弄乱它重要的一行。例如

      ....
      outfile = open(output_filename, 'w')
      lines[-1] = lines[-1].rstrip() + '\n' # make sure last line has a newline
      for line in reversed(lines):
              outfile.write(line)
      ....
      

      【讨论】:

      • 文件的最后一行可能没有换行符
      • 好收获。讨厌的假设。 :) 就个人而言,我认为我会直接处理这种情况,而不是剥离和替换存在的每个换行符。
      • 我考虑过这一点,但我决定只使用一个衬里而不是检查 1 对我来说更实际。你有超过 0 行和 2。最后一行有一个新行
      【解决方案4】:
      with open(your_filename) as h:
          print ''.join(reversed(h.readlines()))
      

      或者,如果您想将其写入其他流:

      with open(your_filename_out, 'w') as h_out:
          with open(your_filename_in) as h_in:
              h_out.write(''.join(reversed(h_in.readlines()))
      

      【讨论】:

        猜你喜欢
        • 2012-10-24
        • 2015-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-18
        • 2022-11-28
        • 1970-01-01
        • 2015-04-18
        相关资源
        最近更新 更多