Pythonic way of write if open is successful

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.


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))

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.


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

Tags:

Python