【问题标题】:Write a program that reads a file and writes out a new file with the lines in reversed order编写一个程序,该程序读取一个文件并以相反的顺序写出一个新文件
【发布时间】:2020-05-04 01:08:18
【问题描述】:

编写一个程序,读取一个文件并以相反的顺序写出一个新文件(即旧文件中的第一行成为新文件中的最后一行。)

我可以使用reverse() 正确反转行,但我无法将输出写入新文件。这是我到目前为止的代码。

f = open("States.txt", "rb")
s = f.readlines()
f.close()
f = open("newstates2.txt", "wb")
x = s.reverse()
f.write(x)

【问题讨论】:

    标签: python python-3.x list reverse


    【解决方案1】:

    reverse() 不返回任何内容。如果要使用reverse(),则必须在之后使用s,而不是为反向列表创建一个新变量。此外,readlines() 返回一个列表,因此您不能直接在其上调用 write(),但您可以遍历它。这是一个更新的版本:

    f = open("States.txt", "rb")
    s = f.readlines()
    f.close()
    f = open("newstates2.txt", "wb")
    s.reverse()
    for line in s:
        f.write(line)
    f.close()
    

    或者,您可以使用reversed(),它会返回相反的版本:

    for line in reversed(s):
        f.write(line)
    

    【讨论】:

      【解决方案2】:
      file = "<path to file>"
      with open(file) as f:
          lines = f.readlines()
      
      reverse_file = "e:\\python\\reversed.txt"
      with open(reverse_file, 'w') as rev:
          rev.writelines(lines[::-1])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-16
        • 1970-01-01
        • 2020-11-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多