python - 如何以不区分大小写的方式将路径的一部分替换为 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\MyApp
为C:\Users\USERNAME\AppData\Roaming\MyForkedApp
,但我的配置文件的路径存储为c:\users\username\appdata\roaming\myapp
,则该功能将不起作用。
解决方案
我找到了这个解决方案:os.path.normcase
在替换src
为dest
.
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)
推荐阅读
- javascript - 反应原生:当我在 TopTabNavigator 中时,Android 后退按钮不会在第一次点击时返回
- python - 即使没有找到数据,每次都试图从漂亮的汤结果中将数据写入列表
- sockets - 我想在套接字上发送 snort3 警报,但是当我运行命令“sudo snort -i ens33 -A alert_unixsock -l /tmp”时,它给出了错误
- django - 如何解决精确查找的 QuerySet 值必须限制为使用切片的一个结果。姜戈
- java - 使用 json 对象映射器在附加的类中填充附加字符串
- jquery - 为什么使用 jquery load() 加载图像时 jquery.lazy 不起作用?
- python - VS 代码是否对不同的 python 终端窗口使用不同的线程?
- c++ - 为什么不能在方法中分配类的数据成员
- daml - 如何在 DAML 中将 Map 的键作为观察者提及?
- git - 项目子模块的maven发布插件