Good day! Please tell me how to implement this: It is necessary to find certain words in the text of the file and replace them with other words, the words that need to be found are contained in the list of old_data, the words with which need to be replaced in new_data

old_data = ['qwe', '123', 'asd'] new_data = ['qwe', '123', 'asd'] 

For a single case when we have one word and we need to change it into one word, I wrote the f-th

  def Params(self, old_data, new_data, file): file = open(mapfile, 'r') text = file.read() file.close() file = open(mapfile, 'w') file.write(text.replace(old_data, new_data)) file.close() 

Everything works, but I don’t understand how to make it take two lists and work with them, I tried to do it with a cycle, but it incorrectly replaces me, in the sense that it doesn’t replace all the elements or then appends extra ones. In general, I ask for help. Thank you in advance!

    1 answer 1

    You can do so, not very nice, but it should work:

     def Params(self, old_data, new_data, file): file1 = open(mapfile, 'r') file2 = open(mapfile, 'w') for line in file1.readlines(): for word_number in range(len(old_data)): line.replace(old_data[word_number], new_data[word_number]) file2.write(line) file1.close() file2.close() 

    UPD:

     def Params(self, old_data, new_data, mapfile): file = open(mapfile, 'r') text = file.read() file.close() for word_number in range(old_data): text.replace(old_data[word_number], new_data[word_number]) file = open(mapfile, 'w') file.write(text) file.close() 
    • There is one of the conditions for using one file. - Rumato
    • Well, if the second option? - spirit
    • Starting your second version of the error: File "models.py", line 20, in Parameters for word_number in range (old_data): TypeError: range () integer result argument, got list. Do not tell me, already then because of what this can happen, as there seems to be no reason for an error. - Rumato
    • one
      Well, of course, len (old_data) is needed there. I corrected above. I just did not check, I quickly wrote on my knee =) They need not an array, but the number of elements in it. - spirit
    • Thank you for help! - Rumato