Case sensitive path comparison in python

11,513

Solution 1

As some commenters have noted, Python doesn't really care about case in paths on case-insensitive filesystems, so none of the path comparison or manipulation functions will really do what you need.

However, you can indirectly test this with os.listdir(), which does give you the directory contents with their actual cases. Given that, you can test if the file exists with something like:

'foo.f90' in os.listdir('PATH_TO_DIRECTORY')

Solution 2

This is something related to your underlying Operating system and not python. For example, in windows the filesystem is case-insensitive while in Linux it is case sensitive. So if I run the same check, as you are running, on a linux based system I won't get true for case insensitive matches -

>>> os.path.exists('F90')
True
>>> os.path.exists('f90')
False                      # on my linux based OS

Still if you really want to get a solution around this, you can do this -

if 'f90' in os.listdir(os.path.dirname('PATH_TO_foo.f90')):
    # do whatever you want to do
Share:
11,513
prakashkut
Author by

prakashkut

Graduate student at UPenn

Updated on June 27, 2022

Comments

  • prakashkut
    prakashkut almost 2 years

    I have to check whether a file is present a particular path in Mac OS X.

    There is a file called foo.F90 inside the directory.

    But when I do if(os.path.exists(PATH_TO_foo.f90)), it returns true and does not notice that f90 is lower case and the file which exists is upper case F90.

    I tried open(PATH_TO_foo.f90, "r"), even this does not work

    How do I get around this?

  • Xiao
    Xiao over 9 years
    Python in Mac OS X is case insensitive if you use os.path.exists
  • Anurag Upadhyaya
    Anurag Upadhyaya over 5 years
    This would not work if there is a nesting of folders and the sensitivity needs to be checked at each level, as the case mismatch could be in the parent of the directory of file direcotry. In that case, the above mentioned check needs to be applied at each level of folder nesting