How to redirect 'print' output to a file using python?

how to redirect url
how to redirect a url to another url in html
how to redirect a domain
301 redirect
how to redirect a url in wordpress
url redirect service
http redirect
redirect on page load

I want to redirect the print to a .txt file using python. I have a 'for' loop, which will 'print' the output for each of my .bam file while I want to redirect ALL these output to one file. So I tried to put

 f = open('output.txt','w'); sys.stdout = f

at the beginning of my script. However I get nothing in the .txt file. My script is:

#!/usr/bin/python

import os,sys
import subprocess
import glob
from os import path

f = open('output.txt','w')
sys.stdout = f

path= '/home/xug/nearline/bamfiles'
bamfiles = glob.glob(path + '/*.bam')

for bamfile in bamfiles:
    filename = bamfile.split('/')[-1]
    print 'Filename:', filename
    samtoolsin = subprocess.Popen(["/share/bin/samtools/samtools","view",bamfile],
                                  stdout=subprocess.PIPE,bufsize=1)
    linelist= samtoolsin.stdout.readlines()
    print 'Readlines finished!'
    ........print....
    ........print....

So what's the problem? Any other way besides this sys.stdout?

I need my result look like:

Filename: ERR001268.bam
Readlines finished!
Mean: 233
SD: 10
Interval is: (213, 252)

The most obvious way to do this would be to print to a file object:

with open('out.txt', 'w') as f:
    print >> f, 'Filename:', filename     # Python 2.x
    print('Filename:', filename, file=f)  # Python 3.x

However, redirecting stdout also works for me. It is probably fine for a one-off script such as this:

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()

Redirecting externally from the shell itself is another good option:

./script.py > out.txt

Other questions:

What is the first filename in your script? I don't see it initialized.

My first guess is that glob doesn't find any bamfiles, and therefore the for loop doesn't run. Check that the folder exists, and print out bamfiles in your script.

Also, use os.path.join and os.path.basename to manipulate paths and filenames.

How to Redirect a Web Page, A redirect is when a web page is visited at a certain URL, it changes to a different URL. For instance, a person visits “website.com/page-a” in their browser and  Using a Redirection Service 1. Check with your web host. If you're unsure of your own coding ability or just want to redirect a URL without digging 2. Pick a 3rd party service. If your web host doesn't offer redirection, there are many other options out there. 3. Follow the instructions from the

You can redirect print with the >> operator.

f = open(filename,'w')
print >>f, 'whatever'     # Python 2.x
print('whatever', file=f) # Python 3.x

In most cases, you're better off just writing to the file normally.

f.write('whatever')

or, if you have several items you want to write with spaces between, like print:

f.write(' '.join(('whatever', str(var2), 'etc')))

5 Ways to Redirect a Website URL, URL redirection is a forwarding technique that should be used to redirect your visitors to the correct website page. Read more on URL redirects  How to Redirect a Web Page HTTP response codes. Every time we enter a URL or make a request from a browser we’re using the Hypertext Transfer HTML redirects. Perhaps the simplest way to redirect to another URL is with the Meta Refresh tag. The content JavaScript redirects. JavaScript is

Python 2 or Python 3 API reference:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used. Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

Since file object normally contains write() method, all you need to do is to pass a file object into its argument.

Write/Overwrite to File
with open('file.txt', 'w') as f:
    print('hello world', file=f)
Write/Append to File
with open('file.txt', 'a') as f:
    print('hello world', file=f)

How to Redirect a Domain: A Complete Guide for Beginners, Want to know how to redirect a domain properly? Check out this step-by-step guide and learn about the types of redirects you can choose from. Click “Go”. After a new tab or window opens, look for the .htaccess file. Right click on the .htaccess file and click on “Code Edit” on the menu. A dialogue box may pop up asking about encoding. Click “Edit” button to continue. Edit the file. “Save Changes” when done.

This works perfectly:

import sys
sys.stdout=open("test.txt","w")
print ("hello")
sys.stdout.close()

Now the hello will be written to the test.txt file. Make sure to close the stdout with a close, without it the content will not be save in the file

How to Redirect a URL, URL redirects are a normal and often desirable part of hosting a website or building a web application. A URL redirect (also known as a domain redirect, web  The simplest way to redirect to another URL is to use an HTML <meta>tag with the http-equiv parameter set to “refresh”. The "content" attribute sets the delay before the browser redirects the user to the new web page. To redirect immediately, set this parameter to “0” seconds for the "content"attribute.

Don't use print, use logging

You can change sys.stdout to point to a file, but this is a pretty clunky and inflexible way to handle this problem. Instead of using print, use the logging module.

With logging, you can print just like you would to stdout, or you can also write the output to a file. You can even use the different message levels (critical, error, warning, info, debug) to, for example, only print major issues to the console, but still log minor code actions to a file.

A simple example

Import logging, get the logger, and set the processing level:

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG) # process everything, even if everything isn't printed

If you want to print to stdout:

ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # or any other level
logger.addHandler(ch)

If you want to also write to a file (if you only want to write to a file skip the last section):

fh = logging.FileHandler('myLog.log')
fh.setLevel(logging.DEBUG) # or any level you want
logger.addHandler(fh)

Then, wherever you would use print use one of the logger methods:

# print(foo)
logger.debug(foo)

# print('finishing processing')
logger.info('finishing processing')

# print('Something may be wrong')
logger.warning('Something may be wrong')

# print('Something is going really bad')
logger.error('Something is going really bad')

To learn more about using more advanced logging features, read the excellent logging tutorial in the Python docs.

HTTP redirect code overview: the redirects guide for SEO, The HTTP redirect code, redirect for short, is a way to forward visitors and search engines from one URL to another. Redirects are used when moving content to  Redirect a Webpage. There are a couple of ways to redirect to another webpage with JavaScript. The most popular ones are location.href and location.replace:

How To Redirect a URL - Website Redirect, URL redirect (URL forwarding) allows you to forward your domain visitors to any URL of your choice. This guide provides steps on how to redirect a URL for a  In HTTP, redirection is triggered by a server sending a special redirect response to a request. Redirect responses have status codes that start with 3, and a Location header holding the URL to redirect to. When browsers receive a redirect, they immediately load the new URL provided in the Location header. Besides the small performance hit of an additional round-trip, users rarely notice the redirection.

URL redirection, URL redirection, also called URL forwarding, is a World Wide Web technique for making a web page available under more than one URL address. When a web  Use a redirect service The simplest option to perform an HTTPS redirect is to use a redirection service. DNSimple provides a redirector service you can use to redirect HTTPS requests. Using a service is the simplest solution, because it requires little configuration and almost no technical knowledge.

How To Redirect to Another Webpage, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  The next steps are: Enter the domain in the given URL field. Click the “Check Redirection” button. The results will be displayed on your device screen in a matter of seconds, which will indicate the type of redirect and its URL.

Comments
  • Why not use f.write(data)?
  • yeah, but I have several data for each bam file (mean, SD,interval...), how can I put these data one by one?
  • f.write(line) - it inserts a line break at the end.
  • @Eran Zimmerman: f.write(line) does not add a line break to the data.
  • You're right, my bad. Could always f.write(line+'\n'), however..
  • Line 8 of your code uses a variable named filename, but it hasn't been created yet. Later in the loop you use it again, but not relevant.
  • Bad practice to change sys.stdout if you don't need to.
  • @my I'm not convinced it is bad for a simple script like this.
  • +1 Haha well you can have my upvote because it's the right way to do it if you absolutely must do it the wrong way... But I still say you should do it with regular file output.
  • How to redirect and print the output on the console ? Seems the "print()" in Python cannot be shown when the stdrr is redirected ?