storing data into a file rather than returning to the terminal

帅比萌擦擦* 提交于 2020-01-06 14:04:08

问题


i have this function: write_reversed_file(input_filename, output_filename) that writes to the given output file the contents of the given input file with the lines in reversed order. i just need the output to be written to the file (output_filename) rather than to the terminal (python shell).

the only part im missing is to store the output into the file. i successfully managed to complete the reversing lines part.

def write_reversed_file(input_filename, output_filename):
    for line in reversed(list(open(filename))):
        print(line.rstrip())    

回答1:


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()



回答2:


It is good practice to use 'with open as' format when working with files since it is automatically closing the file for us. (as recommended in 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")


来源:https://stackoverflow.com/questions/29586063/storing-data-into-a-file-rather-than-returning-to-the-terminal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!