【问题标题】:storing data into a file rather than returning to the terminal将数据存储到文件中而不是返回到终端
【发布时间】:2015-04-12 04:49:44
【问题描述】:

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

【问题讨论】:

  • Shell 输出重定向,如python foo.py > output.txt,可能就足够了。

标签: file python-3.x storing-information


【解决方案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】:

    处理文件时最好使用“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")
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2018-10-24
      • 2011-09-26
      • 2019-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多