python - how to apply a specific regex to a specific line -
i trying apply specific regex on specific line, specified starting key: right have content of file inside python variable 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 replace --------------------------------------------- "path_jamjs": { "changeusername": "te" }, "path_php": { "changeusername": "tes" },
with open ("my.ini", "r") myfile: my_config = myfile.read()
how can apply regex replace on entire file content in my_config replace value @ specific corresponding line, without having loop line line, can regex?
given
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
to
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") myfile: my_config = myfile.read() lines = my_config.splitlines(true) replacements = {"path_jamjs": {"changeusername": "te"}, "path_php": {"changeusername": "tes"}} path, reps in replacements.items(): i, line in enumerate(lines): if line.startswith(path + ':'): key, value in reps.items(): line = line.replace('[' + key + ']', value) lines[i] = line result = ''.join(lines)
Comments
Post a Comment