4

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 3

5

Simply call str or repr on the object, like this:

with open('somefile.txt', 'w') as f:
    f.write(repr(foo()))
Sign up to request clarification or add additional context in comments.

4 Comments

Why do I need io here?
You didn't say whether your program runs on Python 2 or Python 3, and io.open happens to work on both.
so open('somefile','w') as f: f.write() wouldn't work. But io.open would?. That's interesting.
@LelouchLamperouge Sorry, actually 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.
4
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

Is this recommended over what @jbarber has suggested?. Asking purely out of curiosity
I believe so. I never worry about closing the file after reading or writing when I use with.
2

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

the second form is also available in python 2 with the from __future__ import print_function
Accepting @thefourtheye 's answer because of him mentioning the guarantee of file handling closing when with 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
@Lelouch Lamperouge Using the with keyword is often a good idea. At the same time, file objects are automatically garbage collected the last time they are referenced in a program, so you don't always need to close open file objects. Still, it's good practice to close them. The above was abbreviated merely to demonstrate in a concise form how this works. By all means, use a context manager in your code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.