Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<pre><code>import re pat = re.compile('ENABLEPRINTER|PRINTERLIST|PRNT1.PORT') def jojo(mat,dic = {'ENABLEPRINTER':'y', 'PRINTERLIST':'PRNT3', 'PRNT1.PORT':'734'} ): return dic[mat.group()] with open('configfile','rb+') as f: content = f.read() f.seek(0,0) f.write(pat.sub(jojo,content)) f.truncate() </code></pre> <p>Before:</p> <pre><code>ENABLEPRINTER=n PRINTERLIST=PRNT1, PRNT2 PRNT1.PORT=9600 PRNT1.BITS=8 </code></pre> <p>After:</p> <pre><code>y=n PRNT3==PRNT1, PRNT2 734=9600 PRNT1.BITS=8 </code></pre> <p>Too simple to be definitive. Say what are the errors or weaknesses.</p> <p>The advantage of regexes is they can be modulated easily to particular cases.</p> <p>.</p> <p>EDIT:</p> <p>I've just seen that:</p> <p><em>"what i want to do is assign a new value to the variable "</em></p> <p>you could inform of that earlier !</p> <p>Could you give an exemple of file before / after , please.</p> <p>.</p> <p>EDIT 2</p> <p>Here's the code to change the values of certain variables in a file:</p> <pre><code>import re from os import fsync def updating(filename,dico): RE = '(('+'|'.join(dico.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)' pat = re.compile(RE) def jojo(mat,dic = dico ): return dic[mat.group(2)].join(mat.group(1,3)) with open(filename,'rb') as f: content = f.read() with open(filename,'wb') as f: f.write(pat.sub(jojo,content)) #----------------------------------------------------------- vars = ['ENABLEPRINTER','PRINTERLIST','PRNT1.PORT'] new_values = ['y','PRNT3','8310'] what_to_change = dict(zip(vars,new_values)) updating('configfile_1.txt',what_to_change) </code></pre> <p>Before:</p> <pre><code>ENABLEPRINTER=n PRINTERLIST=PRNT1, PRNT2 PRNT1.PORT=9600 PRNT1.BITS=8 </code></pre> <p>After:</p> <pre><code>ENABLEPRINTER=y PRINTERLIST=PRNT3 PRNT1.PORT=8310 PRNT1.BITS=8 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload