Better method of writing stdout to file - python

Normally when I write stdout to a file, I do it like this.
import sys
sys.stdout = open(myfile, 'w')
print "This is in a file."
Now, this method looks ugly to me, and I've heard here and there that there is a better method. If so, what is this better method?

You can also make use of the fact that print can actually wrote to a file.
with open("file.txt", "w") as f:
print("Hello World!", file=fd)
NB: This is Python 3.x Syntax only as print is a function in Python 3.x.
For Python 2.x you can however do:
from __future__ import print_function
Otherwise the same can be achieved with:
with open("file.txt", "w") as fd:
print >> fd, "Hello World!"
See: print() from Python 3.x Docs.

Print directly to the file, using either
with open(myfile, 'w') as fh:
fh.write("This is in a file.\n")
or
with open(myfile, 'w') as fh:
print >>fh, "This is in a file."
or
from __future__ import print_function
with open(myfile, 'w') as fh:
print("This is in a file.", file=fh)

You can do it as shown in the other answers, but it gets kind of old specifying the output file in every statement. So I understand the urge to just redirect sys.stdout. But yes, the way you propose doing it is not as elegant as it could be. Adding proper error handling will make it even uglier. Fortunately, you can create a handy context manager to address these issues:
import sys, contextlib
#contextlib.contextmanager
def writing(filename, mode="w"):
with open(filename, mode) as outfile:
prev_stdout, sys.stdout = sys.stdout, outfile
yield prev_stdout
sys.stdout = prev_stdout
Usage:
with writing("filename.txt"):
print "This is going to the file"
print "In fact everything inside the with block is going to the file"
print "This is going to the console."
Note that you can use the as keyword to get the previous stdout, so you can still print to the screen inside the with block:
with writing("filename.txt") as stdout:
print "This is going to the file"
print >> stdout, "This is going to the screen"
print "This is going to the file again"

Related

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

python: why doesn't this write to file on new line?

def log():
with open("log.txt", 'a') as f:
print ".log.txt"
f.write(msg.encode('utf-8') +"\n")
I call log() several times but doesn't write each msg on new line, and I have no clue why. I tried adding f.close() at the end but that didn't work either. Super frustrating!
I assume you wanted to define log() as log(msg) :). I tried it and it worked on my system (OS X). \n should work, but it's not 100% cross platform so try using os.linesep instead.
# test.py
import os
def log(msg):
with open("log.txt", 'a') as f:
f.write(msg.encode('utf-8') + os.linesep)
log('aaa')
log('bbb')
Then:
$ python test.py
$ cat log.txt
aaa
bbb
You didn't given the msg.
def log():
msg="bhansa"
with open("log.txt", 'a') as f:
print ".log.txt"
f.write(msg.encode('utf-8') +"\n")
log()
or pass the msg in your method.
It's Working Fine.

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.

I want to create a program that reads text file

it does work if I type this on python shell
>>> f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
>>> f.read()
'plpw eeeeplpw eeeeplpw eeee'
>>> f.close()
but if I create a python program, i doesn't work.
import os
f= open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
f.read()
f.close()
i saved this piece of code by using text editor.
if I execute this program in python shell, it shows nothing.
please tell me why..
In the interactive prompt, it automatically prints anything a function call returns. That means the return value of f.read() is printed automatically. This won't happen when you put it in a program however, so you will have to print it yourself to have it show up.
import os
f = open(os.path.join(os.getcwd(), 'test1.txt'), 'r')
print f.read() # use print(f.read()) in Python 3
f.close()
Another suggestion I would make would be to use a with block:
import os
with open(os.path.join(os.getcwd(), 'test1.txt'), 'r') as f:
print f.read()
This means that you won't have to worry about manually closing the file afterwards.

Categories