Reverse os.path.normcase on Windows

Is there an easy way to get a “real” case-sensitive path from the entire downstream path. Like the flip side of os.path.normcase.

For example, consider a directory:

c:\StackOverFlow

If I have the following snippet, how to get d_real?

>>> import os
>>> d = os.path.normcase('C:\\StackOverFlow') # convert to lower case
>>> d
'c:\\stackoverflow'
>>> d_real = ... # should give 'C:\StackOverFlow' with the correct case
+5
source share
5 answers

I would not consider this solution simple, but you can do it:

import os
d = os.path.normcase('C:\\StackOverFlow')
files = os.listdir(os.path.dirname(d))
for f in files:
  if not d.endswith(f.lower()):
    continue
  else
    real_d = os.path.join(os.path.dirname(d), f)

, ( ). ( ). , , os.walk .

+1

lib, / ( ):

def casedpath(path):
    r = glob.glob(re.sub(r'([^:/\\])(?=[/\\]|$)', r'[\1]', path))
    return r and r[0] or path

UNC-:

def casedpath_unc(path):
    unc, p = os.path.splitunc(path)
    r = glob.glob(unc + re.sub(r'([^:/\\])(?=[/\\]|$)', r'[\1]', p))
    return r and r[0] or path
+1

,

import glob
...
if os.path.exists(d):
    d_real = glob.glob(d + '*')[0][:len(d)]
0

, GetShortPathName GetLongPathName. , Windows . ctypes:

def normcase(path):
    import ctypes
    GetShortPathName = ctypes.windll.kernel32.GetShortPathNameA
    GetLongPathName = ctypes.windll.kernel32.GetLongPathNameA
    # First convert path to a short path
    short_length = GetShortPathName(path, None, 0)
    if short_length == 0:
        return path
    short_buf = ctypes.create_string_buffer(short_length)
    GetShortPathName(path, short_buf, short_length)
    # Next convert the short path back to a long path
    long_length = GetLongPathName(short_buf, None, 0)
    long_buf = ctypes.create_string_buffer(long_length)
    GetLongPathName(short_buf, long_buf, long_length)
    return long_buf.value
0

, :

def getRealDirPath(path):
    try:
        open(path)
    except IOError, e:
        return str(e).split("'")[-2]

:

  • dirs
  • , .

, " ".

I tried grep the standard lib to find how they found the real path, but could not find it. Must be in C.

It was a dirty hack a day, next time we will use a regular expression on the stack, because we can :-)

-1
source

All Articles