Why exception from os.path.exists()?

Chris Angelico rosuav at gmail.com
Fri Jun 1 20:05:15 EDT 2018


On Sat, Jun 2, 2018 at 9:54 AM, Steven D'Aprano
<steve+comp.lang.python at pearwood.info> wrote:
> On Sat, 02 Jun 2018 08:50:38 +1000, Chris Angelico wrote:
>
>> My ideal preference would be for True to mean "we know for certain that
>> this exists" and False "we know for certain that this doesn't exist"
>
> We cannot make that promise, because we might not have permission to view
> the file. Since we don't have a three-state True/False/Maybe flag,
> os.path.exists() just returns False.

Being unable to view the file is insignificant, but presumably you
mean we might not have permission to view the containing directory.
And we do get that information:

>>> os.stat("/root/.bashrc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: '/root/.bashrc'
>>> os.stat("/var/.bashrc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/var/.bashrc'

The permissions error is reported differently by stat, but then
exists() just says "oh that's an OS error so we're going to say it
doesn't exist". If you truly want the reliable form of os.path.exists,
it would be this:

try:
    os.stat(path)
    return True
except FileNotFoundError:
    return False

Anything that ISN'T "this file exists" or "this file doesn't exist"
will be signalled with an exception.

ChrisA



More information about the Python-list mailing list