[Tutor] Print to file
Alan Gauld
alan.gauld at btinternet.com
Mon Mar 11 10:44:33 CET 2013
On 11/03/13 08:24, Phil wrote:
> Neither of the following is correct, but the second one seems closer to
> the mark.
>
> >>> print("test", file="/home/phil/Python/words")
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> AttributeError: 'str' object has no attribute 'write'
So this is obviously wrong, it reports an error.
> >>> f = open("/home/phil/Python/words", 'w')
> >>> print("test", file=f
>
But apart from the lack of a closing paren what makes you
think this is wrong? What happened?
> I've used the "with" statement to write and read files but print to file
> could be handy some time.
with is about opening files regardless of what you do
to them so you could use with here too...
with open(("/home/phil/Python/words", 'w') as f:
print( "test", file=f)
I'm not sure what you think the problem is?
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list