簡體   English   中英

如何以不區分大小寫的方式用 windows 上的另一條路徑替換部分路徑

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

我有一個 function,它將路徑的開頭替換為從配置文件讀取的一堆字符串中的另一條路徑。 我這樣做是因為我想將數據目錄移動到一個新位置,這是第一次有人啟動我的應用程序(這是另一個應用程序的分支)。 它在 linux 和 MacOS 上運行良好,但在 Windows 上運行失敗,因為路徑不區分大小寫,而我的替換方法區分大小寫。

這是我的 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)

我可以為 windows 做一個特例,將所有這些字符串傳遞給.lower()步驟,但我想知道是否沒有更好的高級方法來使用pathlib執行此操作。

編輯以添加示例:如果我想將C:\Users\USERNAME\AppData\Roaming\MyApp替換為C:\Users\USERNAME\AppData\Roaming\MyForkedApp ,但我的配置文件的路徑存儲為c:\users\username\appdata\roaming\myapp ,function 將不起作用。

我找到了這個解決方案:在用dest替換src之前,在所有字符串上使用os.path.normcase

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