Python:获取 Windows 中存储的文件名大小写?
尽管 Windows 不区分大小写,但它确实保留文件名的大小写。在Python中,有什么方法可以获取存储在文件系统上的带有大小写的文件名吗?
例如,在Python程序中,我有filename =“texas.txt”,但想知道它实际上存储在文件系统上“TEXAS.txt”,即使这对于各种文件操作来说是无关紧要的。
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?
E.g., in a Python program I have filename = "texas.txt", but want to know that it's actually stored "TEXAS.txt" on the file system, even if this is inconsequential for various file operations.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这是最简单的方法:
Here's the simplest way to do it:
我在使用上面的 win32api 解决方案时遇到了特殊字符问题。对于 unicode 文件名,您需要使用:
I had problems with special characters with the win32api solution above. For unicode filenames you need to use:
这个仅是标准库,可以转换所有路径部分(驱动器号除外):
此外,这个还可以处理 UNC 路径:
注意:它比依赖于文件系统要慢一些> Win API“GetShortPathName”方法,但适用于平台和平台独立于文件系统,并且在 Windows 卷上关闭短文件名生成时也是如此(
fsutil.exe 8dot3name query C:
)。至少推荐后者对于性能关键的文件系统,当不再有 16 位应用程序依赖时:This one is standard library only and converts all path parts (except drive letter):
And this one handles UNC paths in addition:
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:这能回答你的问题吗?
Does this answer your question?
如果你想递归目录
and if you want to recurse directories
您可以使用:
这当然假设您的搜索字符串
'texas.txt'
是小写的。如果不是,您必须先将其转换为小写。You could use:
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.