Output Redirection for Python Code
The query centers around redirecting print statements to a designated text file using Python. Despite employing the sys.stdout technique, the target file remains empty. This article aims to explore the issue and provide alternative solutions.
Utilizing File Objects for Output
The most straightforward approach involves writing directly to a file object:
with open('out.txt', 'w') as f: print('Filename:', filename, file=f) # Python 3.x # print >> f, 'Filename:', filename # Python 2.x
Redirecting Standard Output
Alternatively, stdout redirection can be achieved with the following code:
import sys orig_stdout = sys.stdout f = open('out.txt', 'w') sys.stdout = f for i in range(2): print('i = ', i) sys.stdout = orig_stdout f.close()
Employing Standard Library Context Manager
For Python 3.4 and above, a dedicated context manager can simplify this process:
from contextlib import redirect_stdout with open('out.txt', 'w') as f: with redirect_stdout(f): print('data')
External Output Redirection
Redirecting output externally via the shell is another viable option:
./script.py > out.txt
Additional Considerations
The above is the detailed content of How Can I Redirect Python\'s Print Output to a File and Why Might It Fail?. For more information, please follow other related articles on the PHP Chinese website!