0

我有这个功能: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())    
4

2 回答 2

0

处理文件时最好使用“with 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")
于 2015-04-12T06:12:47.317 回答
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()
于 2015-04-12T04:58:05.853 回答