Creating multiple *.cfg files Python
Question: I'm working with *.cfg files. The file can be read in a text editor like gedit
and has this format:

    
    
    % some comments
    VAR_1= 1
    %
    % More comments
    ANOTHER_VAR= -8
    %
    % comments again
    VAR_THE_COMEBACK= 10
    

I want to create multiple config files just changing VAR_1=
1....2...3.........10. I manage to import the *cfg file without any new import
in python but I'm not getting a way to change just this parameter, saving the
file and creating another one with another value for VAR_1.

my code until now is really simple:

    
    
    import os
    
    os.chdir('/home/leonardo/Desktop')
    
    f = open('file.cfg','r') #if I replace r by w I erase the file ....
    a =  f.read()
    print a.find('1')
    a.replace('1','2') #I tried this but. ... :(
    
    f.close()
    

Any tips ?

Thank you for the help !


Answer: Untested code, but you will get the idea:

    
    
    with open('file.cfg', 'r') as f:
        contents_by_line = f.readlines()
        for var_index, line in enumerate(contents_by_line):
            if line.startswith("VAR_"):
                break
        else:
            raise RuntimeError("VAR_ not found in file")
    
    for var_i, new_cfg_file in ((2,"file2.cfg"),
                                  (3, "file3.cfg")): #add files as you want
       with open(new_cfg_file, "w") as fout:
           for i, line in enumerate(contents_by_line):
               if i == var_index:
                   fout.write("VAR_1=%d\n" % var_i)
               else:
                   fout.write(line)
    

