Python结果输出到txt fi

2024-03-29 07:00:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过两年前发布的代码:

import subprocess  
with open("output.txt", "wb") as f:     
    subprocess.check_call(["python", "file.py"], stdout=f) 

import sys 
import os.path  
orig = sys.stdout
with open(os.path.join("dir", "output.txt"), "wb") as f:
    sys.stdout = f     
    try:
        execfile("file.py", {})     
    finally:
        sys.stdout = orig

它挂起终端直到I ctl-z,然后它使终端崩溃,但打印输出。 我是新的编码和不知道如何解决。我显然做错了什么。谢谢你的帮助。你知道吗


Tags: pathpyimporttxtoutputosaswith
1条回答
网友
1楼 · 发布于 2024-03-29 07:00:16

只需使用write打开并写入文件即可。你知道吗

with open('output.txt', 'w') as f:
    f.write('output text')  # You can use a variable from other data you collect instead if you would like

由于您对编码还不熟悉,我只想告诉您,使用with打开文件实际上会在运行缩进代码后自动关闭它。祝你的项目好运!你知道吗

相关问题 更多 >