osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Python in Blender. Writing information to a file.


On 08Aug2019 22:42, Paul St George <email at paulstgeorge.com> wrote:
>On 08/08/2019 10:18, Peter Otten wrote:
>>The print() function has a keyword-only file argument. So:
>>with open(..., "w") as outstream:
>>     print("Focal length:", bpy.context.object.data.lens, file=outstream)
[...]
>>
>That worked perfectly.
>
>outstream = open(path to my file,'w')
>print(
>whatever I want to print
>file=outstream
>)
>outstream.close()

I just wanted to point out Peter's use of the open context manager:

    with open(..., "w") as outstream:
      print stuff ...

You'll notice that it does not overtly close the file. The file object 
returned from open() is a context manager, the "with" statement arranges 
to close the file when your programme exits the with suite.

Importantly, the close will happen even if the code inside raises an 
exception, which in your "open..print..close" sequence would not reach 
the close call.

So we recommend the "with" form of open() above.

There are circumstances where it isn't useful, but they are very rare.

Cheers,
Cameron Simpson <cs at cskk.id.au>