Search code examples
pythonfilepyevolve

Generate multiple files python


I have a template file, say "template.txt" containing this text for example :

variable_1 = value_1 ;
variable_2 = value_2 ;
variable_3 = value_3 ;

I want to generate multiple files "file#.txt" (where # is the number of the file), in different directories (a new directory for each new file), by modifying the values in the template file each time (these values will be passed on by another Python script (Pyevolve)).

Is that possible (in Python or any other scripting language) ?

Thank you in advance.


Solution

  • 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()