如何在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:UsersUSERNAMEAppDataRoamingMyForkedApp替换C:UsersUSERNAMEAppDataRoamingMyApp,但我的配置文件的路径存储为c:usersusernameappdataroamingmyapp,则该函数将不起作用。

我找到了这个解决方案:在用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)

最新更新