[Tutor] Print to file

Hugo Arts hugo.yoshi at gmail.com
Mon Mar 11 11:38:40 CET 2013


On Mon, Mar 11, 2013 at 10:38 AM, Phil <phil_lor at bigpond.com> wrote:

> On 11/03/13 18:35, Hugo Arts wrote:
>
>> On Mon, Mar 11, 2013 at 9:24 AM, Phil <phil_lor at bigpond.com
>> <mailto:phil_lor at bigpond.com>> wrote:
>>
>>     The usage of print to file is much like the Arduino print to serial
>>     device and it's got me curious to know what the correct syntax is.
>>     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'
>>
>>      >>> f = open("/home/phil/Python/words"**__, 'w')
>>
>>      >>> print("test", file=f
>>
>>     I've used the "with" statement to write and read files but print to
>>     file could be handy some time.
>>
>>
>> The second one should be correct, if you add the closing parenthesis of
>> print. Closing the file afterwards is not strictly required, I think,
>> though it is good practice.
>>
>>
> Thanks Hugo,
>
> I did forget the closing parenthesis but even so the text file "words" was
> created but it's empty.


Make sure you "reply all" so the rest of the mailing list also gets your
response.

Did you exit the interpreter before checking the file contents? If not, the
string you printed might still be in a buffer, waiting to be printed until
the buffer is flushed. Buffers are usually flushed when they are full, when
flush() is called on the buffered object, or when the object is garbage
collected.

Try calling f.flush() or f.close() after you print, and see if that works.

Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130311/c3d68daf/attachment.html>


More information about the Tutor mailing list