'List Indexing - Read File, Find Specific String, Replace String, Output New File

I have the following code, which i am attempting to read any file in, line by line searching for specific values from a list. If a value from within the old list is found, replace the found string with the same index position from old list with that of the new list value. All while maintaining the original document format.

    Old_IDs = ['V-635771', 'V-616641']
    New_IDs = ['V-250319', 'V-220123']

    path = input('Input File Location: ')
    file_type = input('Output File Type: ')

    fin = open(path, "rt")
    fout = open("SomeFile." + file_type, "wt")

    for line in fin
        #read replace the string and write to output file
        fout.write(line.replace('V-635771', 'V-250319')

    fin.close()
    fout.close()

While I have to code working for individual values, I am finding it difficult to properly reference the list and replace the string with the associated index properly.



Solution 1:[1]

If I understand the question correctly, you just need to use the zip function.

   Old_IDs = ['V-635771', 'V-616641']
   New_IDs = ['V-250319', 'V-220123']

   path = input('Input File Location: ')
   file_type = input('Output File Type: ')

   fin = open(path, "rt")
   fout = open("SomeFile." + file_type, "wt")

   for line in fin
       #read replace the string and write to output file
       for old, new in zip(Old_IDs, New_IDs):
           fout.write(line.replace(old, new))

   fin.close()
   fout.close()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zorgoth