Redirect Python Output to Text File
When attempting to redirect print output to a text file using Python, you may encounter difficulties if your chosen method doesn't produce the desired results.
Problem Description
The following code fails to redirect output to a file using sys.stdout:
f = open('output.txt','w') sys.stdout = f path= '/home/xxx/nearline/bamfiles' bamfiles = glob.glob(path + '/*.bam') for bamfile in bamfiles: filename = bamfile.split('/')[-1] print 'Filename:', filename
Solution
Instead of sys.stdout, consider using a file object for printing:
with open('out.txt', 'w') as f: print('Filename:', filename, file=f) # Python 3.x
Alternative Solutions
from contextlib import redirect_stdout with open('out.txt', 'w') as f: with redirect_stdout(f): print('data')
./script.py > out.txt
Additional Considerations
The above is the detailed content of How to Properly Redirect Python Print Output to a Text File?. For more information, please follow other related articles on the PHP Chinese website!