Python in Blender. Writing information to a file.

Cameron Simpson cs at cskk.id.au
Fri Aug 9 18:04:17 EDT 2019


On 09Aug2019 20:53, Paul St George <email at paulstgeorge.com> wrote:
>>>I almost understand.
>>>Are you saying I should change the first line of code to something 
>>>like:
>>>
>>>|outstream = with open(path to my file,'w') # this is invalid syntax|
>>>
>>>and then delete the
>>>outstream.close()
>>
>>No, you should do what Peter wrote:
>>
>>with open("/path/to/file", "w") as outstream:
>>  print(my_stuff, file=outstream)
>>
>Got it! I hadn't taken Peter's advice as code. I thought (well anyway now I have it). So thanks to Peter, Cameron and
>Rhodri.

No worries. You should also got and look up "context manager" in the 
Python docs.

It is a general mechanism where you can write:

  with something as name:
    suite of code

where "something" is an object which implements a context manager.  
Before "suite of code" starts Python calls "something.__enter__" and 
when the interpreter leaves the suite Python calls "something.__exit__".

Notably, it will call __exit__ no matter how you leave the suite: as 
usual, by falling off the end, or early with an exception or a break or 
a continue or a return. The __exit__ function always gets called.

In the case Peter's example, "something" is "open()": the file object 
you get back from open() implements a context manager. Its __enter__ 
function does nothing, but its __exit__ function closes the file.  
Reliably and immediately.

Cheers, Cameron Simpson <cs at cskk.id.au> (formerly cs at zip.com.au)

I swear to god, officer, I'm fixing this bridge. Just go divert traffic.



More information about the Python-list mailing list