Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case sensitive path comparison in python

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?

like image 504
prakashkut Avatar asked Jul 15 '11 16:07

prakashkut


2 Answers

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')
like image 85
Michael C. O'Connor Avatar answered Sep 21 '22 23:09

Michael C. O'Connor


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
like image 42
Pushpak Dagade Avatar answered Sep 19 '22 23:09

Pushpak Dagade