解决os.path.exists大小写不敏感问题

92 阅读1分钟

问题

windows系统中,os.path.exists是大小写不敏感的。 所以有一个叫File.txt的文件,用os.path.exists("file.txt"),返回结果也是true。

原因

在源码中,os.path.exists调用os.stat(),该函数调用系统功能, windows系统的这里是大小写不敏感的,所以该函数也无法做到大小写敏感。 后续测试中pathlibexists函数依然大小写不敏感。

windows大小写不敏感真的很反直觉。不信可以去同一目录下新建一个a.txtA.txt试试哦

解决方法

判断存在后,再获取绝对路径的字符串对比。

from pathlib import Path


def case_sensitive_path_exists(path: str, relative_path=False):
    """
    Check if the path exists in a case-sensitive manner.
    """
    # 构造成Path
    if relative_path:
        path = Path.cwd() / path
    else:
        path = Path(path)
    if not path.exists():
        return False
    # resolved_path是系统里的该文件实际名称
    resolved_path = path.resolve()
    return str(resolved_path) == str(path)
    
print(case_sensitive_path_exists("/rel/path/to/file", True))
print(case_sensitive_path_exists("/abs/path/to/file", False))