Closing a file with stdout being written to it - python

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.

Related

Python "ValueError: I/O operation on closed file" for a text file. But opened

I needed to a library specific output and, so I tired it like this way. But I got "ValueError: I/O operation on closed file." Error.
Here the code example that I tried...
import sys
def print_test():
print("Printing testing print...!")
print("line 01")
print("line 02")
print("line 03")
print("Before capture")
def main():
sys.stdout= open("test.txt", 'w')
print_test()
sys.stdout.close()
main()
print("After capture")
with open('test.txt', 'r') as f:
lines= f.readlines()
for i in lines:
print(i)
if "line 01" in lines:
print("Found line 01")
I did not know this, but after doing sys.stdout.close() it seems you cannot open other files.
However there is a better way to print in a file using print anyway, as the print function accept a file parameter. You can then do something like :
def print_test(f):
print("Printing testing print...!", file=f)
print("line 01", file=f)
print("line 02", file=f)
print("line 03", file=f)
print("Before capture")
def main():
f = open("test.txt", 'w')
print_test(f)
f.close()
main()
The error is caused by this line:
sys.stdout.close()
Effectively you are closing the stdout stream for all following print calls in your program, if you omit to pass a file object to the file parameter.
See definition of print's file keyword argument:
The file argument must be an object with a write(string) method; if it is not present or None, sys.stdout will be used.
After main is finished all following print calls try accessing the re-assigned sys.stdout which now is closed. Thus giving you a ValueError.
Create a local copy of sys.stdout that you can re-assign after your call to print_test to circumvent this:
def main():
stdout = sys.stdout # create local copy of stdout
sys.stdout = open("test.txt", 'w') # change stdout
print_test()
sys.stdout.close()
sys.stdout = stdout # reassign standard output stream to sys.stdout
The other way would be to pass the file object directly to print using the file keyword
myoutput = open("test.txt", "w")
print("Print to file", file=myoutput)
# pass file object to function
def my_print(file):
print("function call to print", file=file)

It says "ValueError: I/O operation on closed file" but i opened it

I want to get the console output in a .txt file.
This is what i have:
import sys
print('some text')
a='moretext.1'.split('.')
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
here it works but in my program don't.
Does someone know what it could be?
It says that that its on line 2 or something
And I already searched on Stackoverflow and in the internet but i cant find anything
Do not mess with sys.stdout, instead open the file and print to it like so:
print('some text')
a='moretext.1'.split('.')
with open('output.txt', 'w') as out:
print(a, file=out)
Multiple ways to do so
1--
python3 myprogram.py > output.txt
2--
import sys
print('some text')
a='moretext.1'.split('.')
output = open('output.txt', 'w')
print(a, file=output)
output.close()
3--
import sys
print('some text')
a='moretext.1'.split('.')
stdout = sys.stdout
sys.stdout = open('output.txt', 'w')
print(a)
sys.stdout.close()
sys.stdout = sys.__stdout__
4--
As #Timur Shtatland suggested you can use a with statement

I have bunch of python print functions. I want to write the output to a file

I am using python 2.7, and currently, I have a python code that prints to screen. I have been piping the output from the python code to a file by using >> command in linux until now. I would like to know if there is a simple method of printing out the output to a file without having to change every print function. Is this possible in python?
def print1():
print "something1"
def print2():
print "something2"
...
def printN():
print "somethingN"
def main():
print1()
print2()
...
printN()
//I would like all the output to be in a file
Found a solution on : How to redirect 'print' output to a file using python?
Below works for my code:
import sys
orig_stdout = sys.stdout
f = open('out.txt', 'w')
sys.stdout = f
main()
sys.stdout = orig_stdout
f.close()

How do I log the contents of print messages to two files with stdout

Looking for some help logging/saving the prints to two file locations as seen below, does anyone know a way to do this?
### Create output file/open it for editing
output_file = open('FILE.txt','w')
output_file1 = open('FILE_APPENDING.txt','a')
## Create a backup of current setting
old_stdout = sys.stdout
sys.stdout = output_file
sys.stdout = output_file1
print "stuff here"
## loop here printing stuff
## Revert python to show prints as normal
sys.stdout=old_stdout
## Close the file we are writing too
output_file.close()
output_file1.close()
Thanks in advance
- Hyflex
You can reassign sys.stdout with some class that writes to multiple files:
class MultiWrite(object):
def __init__(self, *files):
self.files = files
def write(self, text):
for file in self.files:
file.write(text)
def close(self):
for file in self.files:
file.close()
import sys
# no need to save stdout. There's already a copy in sys.__stdout__.
sys.stdout = MultiWrite(open('file-1', 'w'), open('file-2', 'w'))
print("Hello, World!")
sys.stdout.close()
sys.stdout = sys.__stdout__ #reassign old stdout.
Anyway, I agree with Ashwini. It seems that you are searching a hack to obtain something, when you should really use a different approach.
Simply use file.write:
with open('FILE.txt','w') as output_file:
#do something here
output_file.write(somedata) # add '\n' for a new line
with open('FILE_APPENDING.txt','a') as output_file1:
#do something here
output_file1.write(somedata)
help on file.write:
>>> print file.write.__doc__
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.

Why the following python code does not print to file

from sys import stdout
stdout = open('file', 'w')
print 'test'
stdout.close()
does create the file, but it contains nothing.
I had to use
import sys
sys.stdout = open('file', 'w')
print 'test'
sys.stdout.close()
But wouldn't the from ... import... automatically make the name available? Why do I still have to use sys.stdout instead of stdout?
The problem is this: print is equivalent to sys.stdout.write().
So when you do from sys import stdout, the variable stdout won't be used by print.
But when you do
import sys
print 'test'
it actually writes to sys.stdout which is pointing to the file you opened.
Analysis
from sys import stdout
stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the terminal
stdout.close()
import sys
sys.stdout = open('file', 'w')
print 'test' # calls sys.stdout.write('test'), which print to the file
sys.stdout.close()
Conclusion
This works...
from sys import stdout
stdout = open('file', 'w')
stdout.write('test')
stdout.close()

Categories