【问题标题】:How to save the ouput of a python file using subprocess and append all those in a single file?如何使用子进程保存python文件的输出并将所有这些输出附加到一个文件中?
【发布时间】:2025-11-21 16:45:02
【问题描述】:

有一个 python 代码,每次我运行它时都会生成不同的输出。

当我使用 suprocess 在循环中运行该 python 脚本时,如何保存生成的所有输出

我正在使用的代码正在覆盖未附加的文件。


f = open("blah.txt", "w")
subprocess.call(["python","loop.py"], stdout=f)

【问题讨论】:

    标签: python python-3.x loops for-loop subprocess


    【解决方案1】:

    append 模式('a')打开您的文件

    f = open("blah.txt", "a")
    
    Mode    Description
    ---     ---
    'r'     This is the default mode. It Opens file for reading.
    'w'     This Mode Opens file for writing.
    If file does not exist, it creates a new file.
    If file exists it truncates the file.
    'x'     Creates a new file. If file already exists, the operation fails.
    'a'     Open file in append mode.
    If file does not exist, it creates a new file.
    't'     This is the default mode. It opens in text mode.
    'b'     This opens in binary mode.
    '+'     This will open a file for reading and writing (updating)
    

    【讨论】:

      【解决方案2】:

      以追加模式而不是写入模式打开文件

      如果你希望错误也记录在同一个文件中。

      
      f = open("blah.txt", "a")
      
      subprocess.call(["python","loop.py"], stdout=f,stderr=f)
      
      

      【讨论】: