我试图将一个函数的输出存储到 Python 中的一个文件中,我想做的是这样的:
def test():
print("This is a Test")
file=open('Log','a')
file.write(test())
file.close()
但是当我这样做时,我得到了这个错误:
TypeError: argument 1 must be string or read-only character buffer, not None
PD:我正在尝试为我无法修改的功能执行此操作。
最佳答案
每当需要成对执行任何操作时,请使用上下文管理器。
在这种情况下,使用contextlib.redirect_stdout
:
with open('Log','a') as f:
with contextlib.redirect_stdout(f):
test()
编辑:如果你想要它作为一个字符串,使用io.StringIO
:
f = io.StringIO()
with contextlib.redirect_stdout(f):
test()
s = f.getvalue()
关于Python,将函数的输出重定向到文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45885878/