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.

os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write")

It’s supposed to be a one-liner.

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

    os.write(fd,String) if (fd = os.open(str("/var/www/file.js"),os.O_RDWR)) else return HttpResponse("error on write")
                               ^
SyntaxError: invalid syntax `

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 :

try:
  with open('filename.ext', 'w+') as f:
    f.write("Hello world!")
except IOError as e:
  # print("Couldn't open or write to file (%s)." % e) # python 2
  print(f"Couldn't open or write to file ({e})") # py3 f-strings

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