Ask Your Question
0

How can I print to a file instead of standard output?

asked 2014-05-26 13:30:36 -0500

Luis gravatar image

22.9. The print() function

In Python 3, print is a function, not a statement. To make it easier to convert your programs to the new syntax, first use this import statement (introduced in Python 2.6):

from future import print_function Here is the interface to this function:

print(*args, sep=' ', end='\n', file=None) args One or more positional arguments whose values are to be printed.

sep By default, consecutive values are separated by one space. You may specify a different separator string using this keyword argument.

end By default, a newline ("\n") is written after the last value in args. You may use this keywoard argument to specify a different line terminator, or no terminator at all.

file Output normally goes to the standard output stream (sys.stdout). To divert the output to another writeable file, use this keyword argument.

Here's an example. Suppose you are writing three strings named clan, moiety, and distro to a writeable file named spreader, and you want to separate the fields with tab ("\t") characters, and use ASCII CR, Carriage Return ("\r"), as the line terminator. Your call to the print() function would go something like this:

print(clan, moiety, distro, file=spreader, end='\r', sep='\t')

I found this in a Python 2.7 reference guide. I tried this code but it didn't work. I got the message: print('clan', 'moiety', 'distro', file=spreader, end='\r', sep='\t') AttributeError: 'str' object has no attribute 'write'

How can I print to a file instead of standard output?

edit retag flag offensive close merge delete

Comments

Thank you Eli. It solved my problem

Luis gravatar imageLuis ( 2014-05-28 04:24:35 -0500 )edit

2 answers

Sort by ยป oldest newest most voted
1

answered 2014-05-26 18:40:22 -0500

Eli Pack gravatar image

The following works for me, although I have no idea why you would import future and use print() rather than just using write().

from __future__ import print_function
with open('spreader.txt','w') as spreader:
    print("clan", "moiety", "distro", file=spreader, end="\r", sep = "\t")

The alternative would be:

with open('spreader.txt','w') as spreader:
    spreader.write("\t".join(["clan", "moiety", "distro"]) + "\r")
edit flag offensive delete link more
1

answered 2014-07-08 03:47:02 -0500

agastalver gravatar image

Maybe you are looking for this solution:

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

print('Hello!')

This way, you only have to use print to write to the file.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

[hide preview]

Question Tools

Stats

Asked: 2014-05-26 13:30:36 -0500

Seen: 3,224 times

Last updated: Jul 08 '14