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
Release: 2024-11-27 19:43:14
Original
266 people have browsed it

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
Copy after login

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
Copy after login

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')
Copy after login
  • Redirect output externally from the shell:
./script.py > out.txt
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template