Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way of write if open is successful

Tags:

python

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?

like image 357
dylan7 Avatar asked Mar 13 '16 21:03

dylan7


1 Answers

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

like image 120
Loïc Avatar answered Oct 22 '22 11:10

Loïc