简体   繁体   English

如何以不区分大小写的方式用 windows 上的另一条路径替换部分路径

[英]how to replace part of a path with another path on windows in a case insensitive manner

I have a function that replaces the beginning of a path by another path in a bunch of strings read from a configuration file.我有一个 function,它将路径的开头替换为从配置文件读取的一堆字符串中的另一条路径。 I do this because I want to move the data directory to a new place, the first time someone start my application (which is a fork of another application).我这样做是因为我想将数据目录移动到一个新位置,这是第一次有人启动我的应用程序(这是另一个应用程序的分支)。 It works well on linux and MacOS, but fails on Windows because the paths are case insentive and my replacement method is case sensitive.它在 linux 和 MacOS 上运行良好,但在 Windows 上运行失败,因为路径不区分大小写,而我的替换方法区分大小写。

Here is my function:这是我的 function:

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)

I could make a special case for windows, pass all those strings through a .lower() step, but I'm wondering if there isn't a better high-level way of doing this with pathlib .我可以为 windows 做一个特例,将所有这些字符串传递给.lower()步骤,但我想知道是否没有更好的高级方法来使用pathlib执行此操作。

Edit to add an example: if I want to replace C:\Users\USERNAME\AppData\Roaming\MyApp with C:\Users\USERNAME\AppData\Roaming\MyForkedApp , but my config file has the path stored as c:\users\username\appdata\roaming\myapp , the function will not work.编辑以添加示例:如果我想将C:\Users\USERNAME\AppData\Roaming\MyApp替换为C:\Users\USERNAME\AppData\Roaming\MyForkedApp ,但我的配置文件的路径存储为c:\users\username\appdata\roaming\myapp ,function 将不起作用。

I found this solution: use os.path.normcase on all strings prior to replacing src with dest .我找到了这个解决方案:在用dest替换src之前,在所有字符串上使用os.path.normcase

os.path.normcase returns the string unchanged on Mac and Linux, and returns the lowercase string on Windows (and it also normalizes the path separator). 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM