我有一个模板文件,例如包含此文本的“template.txt”:
variable_1 = value_1 ;
variable_2 = value_2 ;
variable_3 = value_3 ;
我想通过每次修改模板文件中的值(这些值将由另一个 Python 脚本 (Pyevolve) 传递。
这可能吗(在 Python 或任何其他脚本语言中)?
先感谢您。
import re
# this regular expression matches lines like " abcd = feg ; "
CONFIG_LINE = re.compile("^\s*(\w+)\s*=\s*(\w+)\s*;")
# this takes { "variable_1":"a", "variable_2":"b", "variable_3":"c" }
# and turns it into "folder_a_b_c"
DIR_FMT = "folder_{variable_1}_{variable_2}_{variable_3}".format
def read_config_file(fname):
with open(fname) as inf:
matches = (CONFIG_LINE.match(line) for line in inf)
return {match.group(1):match.group(2) for match in matches if match}
def make_data_file(variables, contents):
dir = DIR_FMT(**variables)
fname = os.path.join(dir, "data.txt")
with open(fname, "w") as outf:
outf.write(contents)
def main():
variables = read_config_file("template.cfg")
make_data_file(variables, "this is my new file")
if __name__=="__main__":
main()