-1

Suppose I am writing stdout to a file, like this:

sys.stdout = open("file.txt", "w")
# print stuff here

Doing this doesn't work:

sys.stdout.close()

How can I close a file after writing stdout to it?

Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42
  • Keep a reference to the file object and then call `.close()` on that reference. – Ashwini Chaudhary May 04 '14 at 22:30
  • Why does the `with` not do what you want? Your example is opening it to `r`ead, but it will close automatically when you are done with that `with` block. – Andy May 04 '14 at 22:31
  • What OS? Your question doesn't really make sense. Did you mean "how do you stop writing stdout to the file"? – Hamish May 04 '14 at 22:32
  • possible duplicate of [How to safely open/close files in python 2.4](http://stackoverflow.com/questions/3770348/how-to-safely-open-close-files-in-python-2-4) – aruisdante May 04 '14 at 22:32
  • 1
    Just because it *'looks nothing like what I am trying to do'* doesn't mean it doesn't do what you're trying to do. Because as worded, it absolutely does. – aruisdante May 04 '14 at 22:33
  • possible duplicate of [How do I assess if a file is closed?](http://stackoverflow.com/questions/23367673/how-do-i-assess-if-a-file-is-closed) – Ashwini Chaudhary May 04 '14 at 22:33
  • Also possibly a duplicate of [Redirect stdout to a file in Python?](http://stackoverflow.com/questions/4675728/redirect-stdout-to-a-file-in-python) if that's what you're trying to do. – aruisdante May 04 '14 at 22:34
  • If you're using python 3.4, use [`contextlib.redirect_stdout`](https://docs.python.org/dev/library/contextlib.html#contextlib.redirect_stdout). Any other version, just [steal Raymond Hettinger's code](http://hg.python.org/cpython/rev/63a1ee94b3ed). – roippi May 04 '14 at 22:54

3 Answers3

3

I took your question to mean: "How can I redirect sys.stdout to a file?"

import sys

# we need this to restore our sys.stdout later on
org_stdout = sys.stdout

# we open a file
f = open("test.txt", "w")
# we redirect standard out to the file
sys.stdout = f
# now everything that would normally go to stdout
# now will be written to "test.txt"
print "Hello world!\n"
# we have no output because our print statement is redirected to "test.txt"!
# now we redirect the original stdout to sys.stdout
# to make our program behave normal again
sys.stdout = org_stdout
# we close the file
f.close()
print "Now this prints to the screen again!"
# output "Now this prints to the screen again!"

# we check our file
with open("test.txt") as f:
    print f.read()
# output: Hello World!

Is this an answer to your question?

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
3

You can also do this if you want to redirect all print() to a file, which is a fast way and also usefull by my opinion but it could have other effects. If I'm wrong please correct me.

import sys

stdoutold = sys.stdout
sys.stdout = fd = open('/path/to/file.txt','w')
# From here every print will be redirected to the file
sys.stdout = stdoutold
fd.close()
# From here every print will be redirected to console
Padelis
  • 41
  • 6
1

You can do this:

import sys

class writer(object):
    """ Writes to a file """

    def __init__(self, file_name):
        self.output_file = file_name

    def write(self, something):
        with open(self.output_file, "a") as f:
            f.write(something)

if __name__ == "__main__":
    stdout_to_file = writer("out.txt")
    sys.stdout = stdout_to_file
    print "noel rocks"

The file is only open when you write to it like this.

Noelkd
  • 7,686
  • 2
  • 29
  • 43