我有以下代碼,我試圖讀取其中的任何檔案,逐行從串列中搜索特定值。如果找到舊串列中的值,請將找到的字串與舊串列中具有相同索引位置的字串替換為新串列值的索引位置。同時保持原始檔案格式。
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()
雖然我必須為單個值撰寫代碼,但我發現很難正確參考串列并用相關索引正確替換字串。
uj5u.com熱心網友回復:
您可以使用字典作為查找表,也可以讓另一個 for 回圈檢查值串列。
我還建議您with在打開檔案時使用該語法,然后您最終不需要手動關閉它。
with open("foo", "w") as bar:
bar.write("Hello")
在您的示例中使用 for 回圈并假設 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)
用字典作為查找表。
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)
uj5u.com熱心網友回復:
如果我正確理解了這個問題,您只需要使用該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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/479562.html
上一篇:dict[new_key]=[dict[key],new_value]和x=dict[key] [new_value]有什么區別?
