Tell me, please, how to do the following: there is a file, there are two lists, in one the current values ​​that are in the file, the other with new values ​​that need to be replaced with the current one, has actually written the following function:

def createMapFile(old_data, new_data, file): try: if len(old_data) != len(new_data): print 'Наборы параметров не соответствуют друг-другу' else: file = open(file, 'r') # Opens the file in read-mode text = file.read() # Reads the file and assigns the value to a variable file.close() # Closes the file (read session) file = open(mapfile, 'w') i = 0 f = [file.write(text.replace(old_data[i], new_data[i])) for i in range(1, old_data)] # file.write(text.replace(old_data[i], new_data[i])) #replaces all instances of our keyword return file.close() # Closes the file (write session) except: print 'Ошибка:' 

Now an error occurs, although if you take a list and remove the for loop, replacing it with a commented line, then everything works, but with one word, you need a list of words.

  • Python has a structure such as a dictionary. List mapfile in dictionary, read file, break into words and replace existing words (keys) with values ​​(new words) in the dictionary - alexlz
  • Well, at least you would have traced errors, perhaps you would copy here. and it's not at all clear why you use the list generator instead of the usual cycle, can you explain? - actionless

2 answers 2

Never use try / except without specifying a specific exception class. This will lead to the fact that I will be caught absolutely all exceptions, even KeyboardInterrupt. Never use variable counters, there are more elegant methods for this. Do not use list generators, as you use in this code, better use map (). Use iterators in loops. Use the with / as construct; it simplifies the code.

 def createMapFile(old_data, new_data, file_name, map_file): with open(file_name) as file: text = file.read() for index, replaced_data in enumerate(old_data): text = text.replace(replaced_data, new_data[index]) with open(map_file, 'w') as file: file.write(text) 
  • Thanks for the detailed answer, I will take into account the remarks, with Python, so far only a superficially familiar, therefore, with such blunders, the program, Thank you! - Rumato
  • one
    @Ukeo, I, too, have just started to play the python little by little. And like this: def createMapFile (old_data, new_data, file_name, map_file): text = open (file_name). Read () for index, replace_data in enumerate (old_data): text = text.replace (replaced_data, new_data [index]) # I just left open (map_file, 'w'). is write (text) not easier to read? Or are there any pitfalls in this code that I just don’t see yet? Those. What is the deep meaning of using with ? - avp
  • one
    @avp The with method uses the __enter __ () and __exit __ () methods of the object being called, in this case the file object, it guarantees that regardless of whether there is an exception in the code following it or not, the preparatory and final code __enter __ () and __exit__ () will be executed, in this case the file will necessarily be closed. - Ukeo
  • 2
    reduce (lambda x, y: x.replace (* y), zip (old_data, new_data), text) - Daniyar Supiev
  • words = dict(zip(old_data, new_data)); text = regex.sub(r'\b\L<words>\b', lambda m: words[m.group()], text, words=words)' words = dict(zip(old_data, new_data)); text = regex.sub(r'\b\L<words>\b', lambda m: words[m.group()], text, words=words)' - jfs

If there is a function that replaces the words in the string:

 import regex # pip install regex def new_text(old_text, words=dict(zip(old_data, new_data))): return regex.sub(r'\b\L<words>\b', lambda m: words[m.group()], old_text, words=words) 

then the task comes down to replacing strings using this function. For example:

 from pathlib import Path path = Path(filename) path.write_text(new_text(path.read_text())) 

In order not to load the entire file into memory, you can replace it line by line. See How to replace a line in a .txt file through python 3?