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?
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?
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?
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
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.