I have defined the __str__ and __repr__ in my class foo
When I print foo(), it works just fine.
Of course, redefining stdout as a file object and calling print foo() would write the string representation to the file, but is that the most pythonic way to do it?
3 Answers
Simply call str or repr on the object, like this:
with open('somefile.txt', 'w') as f:
f.write(repr(foo()))
4 Comments
io here?io.open happens to work on both.open('somefile','w') as f: f.write() wouldn't work. But io.open would?. That's interesting.open is the better choice here. io.open is the clean version to work with texts (and you can explicitly pick an encoding). But the repr in Python 2.x doesn't return a character, but a bytestring, so one needs the old plain open here. Fixed.with open("Output.txt", "w") as outputFile:
print >>outputFile, foo()
Python docs recommend using with, in this section http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects
It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:
2 Comments
with.If you are using Python 2.7, you can temporarily direct your print to stdout in this fashion:
>>> print >> open('test.txt', 'w'), 'test string'
If you are using Python 3.3, you can temporarily direct your print to stdout in this fashion:
>>> print('test string', file=open('test.txt', 'w'))
Both of these methods allow you to switch the output temporarily.
As deque starmap partial setattr has pointed out below, in Python 2.7, you can also temporarily direct your print to stdout in this fashion:
>>> from __future__ import print_function
>>> print('test string', file=open('test.txt', 'w'))
3 Comments
from __future__ import print_functionwith is used. How would you go about testing if the handle is still open after the print finishes? There isn't a way to reference the object without giving it a name, Right? Maybe id can be used somehow