Skip to content
Advertisement

Pythonic way of write if open is successful

I am looking for a pythonic way to create and write to file if opening it was successful or else return an error if not (e.g. permission denied).

I was reading here What’s the pythonic way of conditional variable initialization?. Although I’m not sure this method works as I have attempted to test it.

JavaScript

It’s supposed to be a one-liner.

When I do the above I get a syntax error as such:

JavaScript

Is there a more and correct pythonic one-line or two-liner to be able to achieve this?

Advertisement

Answer

I’d do something like this :

JavaScript

edits along the comments, thank you for your input!

2022-03 edit for f-strings

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement