首页 > 解决方案 > 如何以不区分大小写的方式将路径的一部分替换为 Windows 上的另一条路径

问题描述

我有一个函数,它用从配置文件读取的一堆字符串中的另一个路径替换路径的开头。我这样做是因为我想在有人第一次启动我的应用程序(这是另一个应用程序的分支)时将数据目录移动到一个新位置。它在 linux 和 MacOS 上运行良好,但在 Windows 上失败,因为路径不区分大小写,而我的替换方法区分大小写。

这是我的功能:

def replace_src_dest_in_config(src: str, dest: str, config: dict):
    """Replace all occurrences of the string src by the str dest in the
    relevant values of the config dictionary.
    """
    # adjust all paths to point to the new user dir
    for k, v in config.items():
        if isinstance(v, str) and v.startswith(src):
            config[k] = v.replace(src, dest)

我可以为 windows 做一个特殊情况,通过一个.lower()步骤传递所有这些字符串,但我想知道是否没有更好的高级方法来执行此操作pathlib

编辑添加一个示例:如果我想替换C:\Users\USERNAME\AppData\Roaming\MyAppC:\Users\USERNAME\AppData\Roaming\MyForkedApp,但我的配置文件的路径存储为c:\users\username\appdata\roaming\myapp,则该功能将不起作用。

标签: pythonwindows

解决方案


我找到了这个解决方案:os.path.normcase在替换srcdest.

os.path.normcase在 Mac 和 Linux 上返回未更改的字符串,在 Windows 上返回小写字符串(它还规范化路径分隔符)。

def replace_src_dest_in_config(src: str, dest: str, config: dict):
    norm_src = os.path.normcase(src)
    norm_dest = os.path.normcase(dest)
    # adjust all paths to point to the new user dir
    for k, v in config.items():
        if isinstance(v, str):
            norm_path = os.path.normcase(v)
            if norm_path.startswith(norm_src):
                config[k] = norm_path.replace(norm_src, norm_dest)

推荐阅读