我正试图在特定的行上应用特定的regex,这是由启动键指定的:现在,我在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中的整个文件内容上应用regex替换,该文件内容将替换特定对应行的值,而不必逐行循环,是否可以使用regex?执行此操作?
给定的
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发布于 2013-05-09 16:15:09
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)https://stackoverflow.com/questions/16466209
复制相似问题