[英]how to apply a specific regex to a specific line
我试图在由开始键指定的特定行上应用特定的正则表达式:现在我将文件内容包含在python变量my_config中
file content
---------------------------------------------
[paths]
path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe
values to replace
---------------------------------------------
"path_jamjs": { "changeUsername": "Te" },
"path_php": { "changeUsername": "TeS" },
with open ("my.ini", "r") as myfile:
my_config = myfile.read()
如何在将要替换特定对应行上的值的my_config中的整个文件内容上应用正则表达式替换,而不必一行一行地循环,我可以使用正则表达式来做到这一点吗?
特定
path: path_php
key: changeUsername
value: Te
更改
path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/[changeUsername]/php/php.exe
至
path_jamjs: C:/Users/[changeUsername]/AppData/Roaming/npm/node_modules/jamjs/bin/jam.js
path_php: C:/Te/php/php.exe
with open ("my.ini", "r") as myfile:
my_config = myfile.read()
lines = my_config.splitlines(True)
replacements = {"path_jamjs": {"changeUsername": "Te"},
"path_php": {"changeUsername": "TeS"}}
for path, reps in replacements.items():
for i, line in enumerate(lines):
if line.startswith(path + ':'):
for key, value in reps.items():
line = line.replace('[' + key + ']', value)
lines[i] = line
result = ''.join(lines)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.