On 09/08/2019 15:59, Rhodri James wrote:
On 09/08/2019 14:54, Paul St George wrote:

On 09/08/2019 04:09, Cameron Simpson wrote:
On 08Aug2019 22:42, Paul St George <em...@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 <c...@cskk.id.au>

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.

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to