【问题标题】:How can i reverse a file line by line? [duplicate]如何逐行反转文件? [复制]
【发布时间】:2018-09-13 12:57:39
【问题描述】:

我一直在尝试解决这个问题,但我无法解决

我想反转一个看起来像这样的文件

Hello there
My name is
How are you

通过颠倒它,我的意思是我希望它在之后看起来像这样

there Hello
is name My
you are How

我试过了

 lines = []
with open('test.txt', "r") as f:
    lines = f.readlines()

with open('testrev.txt', 'w') as f:
    for line in reversed(lines):
        f.write(line)

并通过添加

f.write(line[::-1])

对不起,我就是想不通,我们会非常感谢您的帮助

【问题讨论】:

  • 提示:不要同时读取和写入文件。使用其他输出文件或读取、处理、重新打开和写入。
  • 副本讨论了反转给定行的单词,而不是字母。 Python 中的简短版本是 " ".join(line.split()[::-1]) + "\n"
  • @KlausD.:他们从一个文件读取,然后写入另一个文件。

标签: python


【解决方案1】:

您可以使用您编写的代码,但需要调整以下内容:

with open('testrev.txt', 'w') as f:
    for line in lines:
        rev_line = reversed(line.split())
        f.write(" ".join(rev_line) + "\n")

这会颠倒每行中单词的顺序,同时保持行的顺序。

【讨论】:

    【解决方案2】:

    只是补上你写的代码:

    lines = []
    with open('test.txt', "r") as f:
        lines = f.readlines()
    
    with open('testrev.txt', 'w') as f:
        for line in lines:
            f.write(" ".join(reversed(line.split()))+"\n")
    

    如果您使用的是 Python 3,最后一行也可能如下所示:

            f.write(*reversed(line.split())+"\n")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-30
      • 2020-02-18
      • 2011-04-06
      • 2022-11-24
      • 2021-08-20
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多