编写一个程序,读取一个文件并以相反的顺序写出一个新文件

Write a program that reads a file and writes out a new file with the lines in reversed order

Write a program that reads a file and writes out a new file with the lines in reversed order (i.e. the first line in the old file becomes the last one in the new file.)

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

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

reverse() 没有 return 任何东西。如果要使用 reverse(),则必须在之后使用 s 而不是为反向列表创建新变量。此外,readlines() return 是一个列表,因此您不能直接对其调用 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() 来实现 return 反向版本:

for line in reversed(s):
    f.write(line)
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])