-3

I have a .txt file with a variable called id=

How can I write a script that will look into that .txt file, find id= and insert a string right after the =?

I do have a separate .py file called dictionary that contains a dictionary with the purpose of finding and replacing certain words in the .txt file.

Could I also use this dictionary as a way to find and insert?

umn
  • 431
  • 6
  • 17

1 Answers1

0

Read the file line by line, if line has 'id=' replace it with the builtin replace method of str and write the new line, else write the old line.

with open(path_to_file) as fp:
  with open(path_to_new_file, 'w') as nfp:
    string = "whatever"
      for line in fp: 
        if "id=" in line:
          new_line = line.replace("id=", f"id={string}")
          print(f"replacing {line} with {new_line}")
          nfp.write(new_line)
        else: 
          nfp.write(line) 
Fakher Mokadem
  • 1,059
  • 1
  • 8
  • 22