Windows 10下如何让pathlib的Path类以大小写敏感模式工作?
在Windows 10 x64上创建大小写敏感的目录
问题背景
你正在使用pathlib模块检查并创建目录,代码如下:
from pathlib import Path file_or_directory=Path(path+"/"+mobile_no+"/"+ "CV") if file_or_directory.exists(): print(mobile_no+"/"+"CV" + " directory exits---") else: print(mobile_no+"/"+"CV" + " --directory does not exit. --So Create it") # 修正了原代码的语法错误 file_or_directory.mkdir(parents=True, exist_ok=True)
但遇到了Windows文件系统默认大小写不敏感的问题:已经创建了CV目录,无法创建独立的cv目录。
解决方案:为特定目录开启大小写敏感性
Windows 10 x64支持为**单个目录(及子目录)**开启大小写敏感性,全局默认关闭。下面是具体操作步骤:
1. 用管理员权限开启目标父目录的大小写敏感
打开管理员PowerShell,执行以下命令(替换为你的基础父目录路径):
fsutil file setCaseSensitiveInfo "C:\Your\Base\Directory" enable
注意:
- 该设置会被目录下的所有子目录继承
- 一旦开启,除非删除整个目录,否则无法关闭这个目录的大小写敏感性(Windows的设计限制)
2. 调整你的Python代码适配大小写敏感
首先修正原代码的语法错误(原代码中print语句里的CV未加引号),然后可以分别处理CV和cv目录:
from pathlib import Path # 替换为你的实际基础路径 base_path = "C:\\Your\\Base\\Directory" mobile_no = "123456" # 处理大写CV目录 dir_cv_upper = Path(base_path, mobile_no, "CV") if dir_cv_upper.exists(): print(f"{mobile_no}/CV directory exists---") else: print(f"{mobile_no}/CV --directory does not exist. --Creating it now") dir_cv_upper.mkdir(parents=True, exist_ok=True) # 处理小写cv目录 dir_cv_lower = Path(base_path, mobile_no, "cv") if dir_cv_lower.exists(): print(f"{mobile_no}/cv directory exists---") else: print(f"{mobile_no}/cv --directory does not exist. --Creating it now") dir_cv_lower.mkdir(parents=True, exist_ok=True)
3. 验证效果
- 在PowerShell中进入目标目录,执行
dir命令,会看到CV和cv两个独立目录 - Python代码中的
exists()方法现在会正确区分大小写,不会再把CV和cv视为同一个目录
内容的提问来源于stack exchange,提问作者S.Rakin
相关产品推荐
相关产品推荐

