Home > Mobile >  List Indexing - Read File, Find Specific String, Replace String, Output New File
List Indexing - Read File, Find Specific String, Replace String, Output New File

Time:05-21

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.

CodePudding user response:

You could either use a dictionary as a look-up table or have another for-loop checking the list of values.

I also recommend you use the with syntax when opening a file, then you don't need to manually close it in the end.

with open("foo", "w") as bar:
    bar.write("Hello")

Using a for-loop in your example and assuming Old_IDs and New_IDs will be of the same length and any index in Old_IDs will correspond with the proper New_IDs index.

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

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

with open(path, "rt") as file:
    fin = file.readlines()

with open("SomeFile."   file_type, "wt") as fout:
    for line in fin:
        for i, ID in enumerate(Old_IDs):
            if ID in line:
                line.replace(ID, New_IDs[i])
        fout.write(line)

With a dictionary as a look-up table.

ID_map = {'V-635771': 'V-250319', 'V-616641': 'V-220123'}

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

with open(path, "rt") as file:
    fin = file.readlines()

with open("SomeFile."   file_type, "wt") as fout:
    for line in fin:
        for ID in ID_map:
            if ID in line:
                line.replace(ID, ID_map[ID])
        fout.write(line)

CodePudding user response:

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()
  • Related