Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I get the correctly-cased path for a file?

Windows uses case-insensitive file names, so I can open the same file with any of these:

r"c:\windows\system32\desktop.ini" r"C:\WINdows\System32\DESKTOP.ini" r"C:\WiNdOwS\SyStEm32\DeSkToP.iNi" 

etc. Given any of these paths, how can I find the true case? I want them all to produce:

r"C:\Windows\System32\desktop.ini" 

os.path.normcase doesn't do it, it simply lowercases everything. os.path.abspath returns an absolute path, but each of these is already absolute, and so it doesn't change any of them. os.path.realpath is only used to resolve symbolic links, which Windows doesn't have, so it's the same as abspath on Windows.

Is there a straightforward way to do this?

like image 604
Ned Batchelder Avatar asked Sep 11 '10 19:09

Ned Batchelder


People also ask

How do I get the file path of a text file in Python?

In order to obtain the Current Working Directory in Python, use the os. getcwd() method. This function of the Python OS module returns the string containing the absolute path to the current working directory.

How do I get the path of a Python file executed?

Run it with the python (or python3 ) command. You can get the absolute path of the current working directory with os. getcwd() and the path specified with the python3 command with __file__ . In Python 3.8 and earlier, the path specified by the python (or python3 ) command is stored in __file__ .


1 Answers

Ned's GetLongPathName answer doesn't quite work (at least not for me). You need to call GetLongPathName on the return value of GetShortPathname. Using pywin32 for brevity (a ctypes solution would look similar to Ned's):

>>> win32api.GetLongPathName(win32api.GetShortPathName('stopservices.vbs')) 'StopServices.vbs' 
like image 153
Paul Moore Avatar answered Sep 23 '22 03:09

Paul Moore