Python Forum
Unexpected output write - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Unexpected output write (/thread-7646.html)



Unexpected output write - minmanrox - Jan-19-2018

I've just taken up coding and have been teaching myself out of Simon Monk's "Programming the Raspberry Pi" book. On p79, he demonstrates how to write a file in the python shell. When I copy his code into my shell, instead of writing a file, it gives me the length of the string I tried to write.
I've tried different files, different variable names, restarting python, and trying different strings, but it's always the same result. I'm running python 3 on Raspbian.
My shell looks like this:
>>> f = open('test.txt', 'w')
>>> f.write('words')
5
>>>
hoping you can help
[email protected]


RE: Unexpected output write - Windspar - Jan-19-2018

That the right result. If you total every write. Then you know how many chars are in the file.
You have to close file. closing a file will flush data. Saving it to file.
If you don't close file. It a memory leak.


RE: Unexpected output write - Larz60+ - Jan-19-2018

better to use:
with open('test.txt', 'w') as f:
    f.write(...)
that way you don't have to remember to close as it's done automatically


RE: Unexpected output write - minmanrox - Jan-19-2018

Awesome makes sense. Thank you