Hello, please help with the task.

There is a file "primer.txt" , there is a line in it (the line number is dynamic, since data is constantly recorded in it)

"StrokaNaZamenu=123" 

The value after is also dynamic. It is necessary to replace in this file either the numbers (for example, 999) or you can replace the whole line by replacing the old one with the new "StrokaNaZamenu =" + "999".

Thank.

  • You are welcome. The normal replacement method is to rewrite to another file, to delete the old one, to rename the new one to the old one. Do you like this option? (one). Why necessarily python? (2) - alexlz
  • If the file contains all values ​​of the form: param = value, then you can use (ConfigParser) [ docs.python.org/2/library/configparser.html] Read the config, replace the value, save the config. If you do not have sections, they can be easily emulated - BOPOH
  • and somewhere like that s = "StrokaNaZamenu = 123" arr = s.split ('=', 2) # arr is now an array with two elements. new_s = arr [0] + '=' + 999 - KoVadim
  • The normal replacement method is to rewrite to another file, to delete the old one, to rename the new one to the old one. Do you like this option? (one). Yes, that’s fine too. - drenadan
  • @drenadan how the template (insert paste to taste): import os, tempfile a = "StrokaNaZamenu = 999" a1 = a.split ('=') fn = "primer.txt" f = open (fn, 'rt') f1 = tempfile.NamedTemporaryFile (mode = 'w', delete = False) for s in f: s1 = s.rstrip ('\ n') if a1 [0] in s1: print (a, file = f1) else: print (s1, file = f1) f.close () st_mode = os.stat (fn) f1.close () os.remove (fn) os.rename (f1.name, fn) os.chmod (fn, st_mode. st_mode) On sed it looks much shorter and prettier. - alexlz

0