我有这个函数:write_reversed_file(input_filename, output_filename)
向给定的输出文件写入给定输入文件的内容,其中行的顺序相反。我只需要将输出写入文件(output_filename
)而不是终端(python shell)。
我唯一缺少的部分是将输出存储到文件中。 我成功地设法完成了倒车线部分。
def write_reversed_file(input_filename, output_filename):
for line in reversed(list(open(filename))):
print(line.rstrip())
答案 0 :(得分:0)
def write_reversed_file(input_filename, output_filename):
s = ""
f = open(input_filename,"r")
lines = f.read().split("\n")
f.close()
for line in reversed(lines):
s+=line.rstrip()+"\n"
f = open(outPutFile.txt,"w")
f.write(s)
f.close()
答案 1 :(得分:0)
优良作法是使用' open as'处理文件时格式化,因为它会自动为我们关闭文件。 (按照docs.python.org的建议)
def write_reversed_file(input_filename, output_filename):
with open(output_filename, 'w') as f:
with open(input_filename, 'r') as r:
for line in reversed(list(r.read())):
f.write(line)
write_reversed_file("inputfile.txt", "outputfile.txt")