Pythonic way of write if open is successful

Question:

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?

Asked By: dylan7

||

Answers:

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 write to file ({e})") # py3 f-strings

edits along the comments, thank you for your input!

2022/03 – edit for f-strings

Answered By: Loïc

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.

Answered By: Ami Tavory

If you want to be Pythonic, always go for readability when designing your code. To be honest, there is absolutely nothing wrong with wrapping something in a try/except and controlling your logic accordingly.

AKA, EAFP -> Easier to Ask for Forgiveness than Permission.

Furthermore, when you are writing to a file, you are always better off using a context manager.

So, this can easily translate in to something like this:

try:
    with open('your_file', 'w') as f:
        f.write(your_data)
except (OSError, IOError) as exc:
    print("Your file could not be written to, your exception details are: {}".format(exc))
Answered By: idjaw

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.

Answered By: Bharel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.