I'm trying to store the output of a Function into a file in Python, what I am trying to do is something like this:
def test():
print("This is a Test")
file=open('Log','a')
file.write(test())
file.close()
But when I do this I get this error:
TypeError: argument 1 must be string or read-only character buffer, not None
PD: I'm trying to do this for a function I can't modify.
Whenever any operation would need to be performed in pairs, use a context manager.
In this case, use contextlib.redirect_stdout
:
with open('Log','a') as f:
with contextlib.redirect_stdout(f):
test()
Edit: if you want it as a string, use io.StringIO
:
f = io.StringIO()
with contextlib.redirect_stdout(f):
test()
s = f.getvalue()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With