Difference between os.path.isdir and Path.is_dir

Chris Angelico rosuav at gmail.com
Thu Jul 25 12:14:46 EDT 2019


On Fri, Jul 26, 2019 at 1:30 AM Kirill Balunov <kirillbalunov at gmail.com> wrote:
>
>  Hi all! It is expected that:
> ```
> >>> import os
> >>> from pathlib import Path
> >>> dummy = " "   # or "" or "     "
> >>> os.path.isdir(dummy)
> False
> >>> Path(dummy).is_dir()
> True
> ```
>
> or was it overlooked?
>

Was not aware of that. A bit of digging shows that asking to convert
an empty path to an absolute one will give you the name of the current
directory (whether you use os.path or pathlib.Path), but os.path.isdir
starts by seeing if it can os.stat the given path, and if that fails,
it returns False (because if something doesn't exist, it can't be a
directory).

As a workaround, you could simply call
os.path.isdir(os.path.abspath(x)) to get consistent results. I'm not
sure if this is considered an important enough bug to actually fix, or
if it's merely a curiosity that occurs when you trigger undocumented
behaviour.

ChrisA



More information about the Python-list mailing list