16

尽管 Windows 不区分大小写,但它确实在文件名中保留了大小写。在 Python 中,有没有办法在文件系统中存储带大小写的文件名?

例如,在 Python 程序中,我有 filename = "texas.txt",但想知道它实际上存储在文件系统上的 "TEXAS.txt",即使这对于各种文件操作来说都是无关紧要的。

4

6 回答 6

10

这是最简单的方法:

>>> import win32api
>>> win32api.GetLongPathName(win32api.GetShortPathName('texas.txt')))
'TEXAS.txt'
于 2010-01-22T04:33:51.620 回答
6

我在上面的 win32api 解决方案中遇到了特殊字符的问题。对于 unicode 文件名,您需要使用:

win32api.GetLongPathNameW(win32api.GetShortPathName(path))
于 2011-10-01T19:33:50.337 回答
3

这只是标准库,并转换所有路径部分(驱动器号除外):

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

注意:它比依赖于文件系统fsutil.exe 8dot3name query C:的 Win API“GetShortPathName”方法要慢一些,但可以独立于平台和文件系统工作,并且在 Windows 卷 ( )上关闭短文件名生成时也是如此。当没有 16 位应用程序不再依赖它时,建议至少将后者用于性能关键文件系统:

fsutil.exe behavior set disable8dot3 1
于 2016-08-25T08:44:54.437 回答
1
>>> import os
>>> os.listdir("./")
['FiLeNaMe.txt']

这回答了你的问题了吗?

于 2010-01-21T23:48:43.397 回答
1

你可以使用:

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')

这当然假设您的搜索字符串'texas.txt'是小写的。如果不是,您必须先将其转换为小写。

于 2010-01-21T23:50:06.920 回答
1

如果你想递归目录

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 )
于 2010-01-22T00:48:03.987 回答