尽管 Windows 不区分大小写,但它确实在文件名中保留了大小写。在 Python 中,有没有办法在文件系统中存储带大小写的文件名?
例如,在 Python 程序中,我有 filename = "texas.txt",但想知道它实际上存储在文件系统上的 "TEXAS.txt",即使这对于各种文件操作来说都是无关紧要的。
这是最简单的方法:
>>> import win32api
>>> win32api.GetLongPathName(win32api.GetShortPathName('texas.txt')))
'TEXAS.txt'
我在上面的 win32api 解决方案中遇到了特殊字符的问题。对于 unicode 文件名,您需要使用:
win32api.GetLongPathNameW(win32api.GetShortPathName(path))
这只是标准库,并转换所有路径部分(驱动器号除外):
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
>>> import os
>>> os.listdir("./")
['FiLeNaMe.txt']
这回答了你的问题了吗?
你可以使用:
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'
是小写的。如果不是,您必须先将其转换为小写。
如果你想递归目录
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 )