Python: getting filename case as stored in Windows?

前端 未结 6 1682
终归单人心
终归单人心 2020-12-17 15:01

Though Windows is case insensitive, it does preserve case in filenames. In Python, is there any way to get a filename with case as it is stored on the file system?

相关标签:
6条回答
  • 2020-12-17 15:07

    You could use:

    import os
    a = os.listdir('mydirpath')
    b = [f.lower() for f in a]
    try:
        i = b.index('texas.txt')
        print a[i]
    except ValueError:
        print('File not found in this directory')
    

    This of course assumes that your search string 'texas.txt' is in lowercase. If it isn't you'll have to convert it to lowercase first.

    0 讨论(0)
  • 2020-12-17 15:10

    I had problems with special characters with the win32api solution above. For unicode filenames you need to use:

    win32api.GetLongPathNameW(win32api.GetShortPathName(path))
    
    0 讨论(0)
  • 2020-12-17 15:12

    and if you want to recurse directories

    import os
    path=os.path.join("c:\\","path")
    for r,d,f in os.walk(path):
        for file in f:
            if file.lower() == "texas.txt":
                  print "Found: ",os.path.join( r , file )
    
    0 讨论(0)
  • 2020-12-17 15:19

    Here's the simplest way to do it:

    >>> import win32api
    >>> win32api.GetLongPathName(win32api.GetShortPathName('texas.txt')))
    'TEXAS.txt'
    
    0 讨论(0)
  • 2020-12-17 15:22
    >>> import os
    >>> os.listdir("./")
    ['FiLeNaMe.txt']
    

    Does this answer your question?

    0 讨论(0)
  • 2020-12-17 15:34

    This one is standard library only and converts all path parts (except drive letter):

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

    And this one handles UNC paths in addition:

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

    Note: It is somewhat slower than the file system dependent Win API "GetShortPathName" method, but works platform & file system independent and also when short filename generation is switched off on Windows volumes (fsutil.exe 8dot3name query C:). The latter is recommended at least for performance critical file systems when no 16bit apps rely anymore on that:

    fsutil.exe behavior set disable8dot3 1
    
    0 讨论(0)
提交回复
热议问题