列表索引 - 读取文件、查找特定字符串、替换字符串、输出新文件

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

我有以下代码,我试图读取其中的任何文件,逐行搜索列表中的特定值。如果找到旧列表中的值,则将旧列表中具有相同索引位置的找到的字符串替换为新列表值的字符串。同时保持原始文档格式。

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

虽然我必须为单个值编写代码,但我发现很难正确引用列表并将字符串正确替换为关联的索引。

如果我理解正确,你只需要使用zip函数即可。

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

您可以使用字典作为 look-up table 或者让另一个 for-loop 检查值列表。

我也建议你在打开文件时使用with语法,这样你最后就不需要手动关闭它了。

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

在您的示例中使用 for-loop 并假设 Old_IDs 和 New_IDs 的长度相同,并且 Old_IDs 中的任何索引都将对应于正确的 New_IDs索引。

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)

用字典作为 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)