Home >Backend Development >Python Tutorial >How to Properly Redirect Python Print Output to a Text File?

How to Properly Redirect Python Print Output to a Text File?

Susan Sarandon
Susan SarandonOriginal
2024-11-27 19:43:14316browse

How to Properly Redirect Python Print Output to a Text File?

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

  • Use a context manager to redirect output:
from contextlib import redirect_stdout

with open('out.txt', 'w') as f:
    with redirect_stdout(f):
        print('data')
  • Redirect output externally from the shell:
./script.py > out.txt

Additional Considerations

  • Ensure that the glob function is locating the intended files.
  • Properly manipulate file paths using os.path.join and os.path.basename.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn