Q:

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?

A:

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)

edits along the comments, thank you for your input!

A:

Instead of nesting the try and with statements (and missing the IOError on the way if the inner code raises one), I highly suggest this syntax. It causes one less nesting and makes sure that the IOError occurred because of the open. That way, you have no chance of catching an unwanted exception, and you have much more control.
f = None
try:
    f = open('file', 'w+')
except IOError:
    print("Couldn't open the file")
else:
    f.write('You are opened')
finally:
    if f: f.close()

There is no real pythonic way for doing it as a one liner, and it's generally a good idea to avoid long one liners.

A:

Since you're asking about what the Pythonic was of doing something, I think that you should consider the Ask Forgiveness, Not Permission paradigm. Namely, just perform the operation, and catch the appropriate exception if it didn't work.
For example, 
In [1]: open('/usr/tmp.txt', 'w').write('hello')
---------------------------------------------------------------------------
IOError                                   Traceback (most recent call last)
<ipython-input-1-cc55d7c8e6f9> in <module>()
----> 1 open('/usr/tmp.txt', 'w').write('hello')

IOError: [Errno 13] Permission denied: '/usr/tmp.txt'

If there was no permission to do the op, an IOError will be thrown. Just catch it, then.
try:
    open('/usr/tmp.txt', 'w').write('hello')
except IOError:
    ...

Alex Martelli once talked about this, and described some inherent fallacies about checking permissions. There's an inherent race in these matters. You could always have permission to write when you opened the file, but not later when you attempted to write. You'll have to deal with exceptions anyway, so you might as well just build with them.

