我正在尝试在特定行上应用特定的正则表达式,由起始键指定: 现在我的文件内容在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
CHANGE
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
答案 0 :(得分:2)
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)