循环遍历字典以替换文本文件中的多个值

我正在尝试更改文本文件中的几个十六进制值。我制作了一个 CSV,其中一列包含原始值,另一列包含新值。


我的目标是编写一个简单的 Python 脚本,根据第一列在文本文件中查找旧值,并在第二列中用新值替换它们。


我正在尝试使用字典来促进replace()我通过循环 CSV 创建的字典。构建它非常容易,但是使用它来执行一个任务replace()还没有成功。当我在脚本运行后打印出这些值时,我仍然看到原始值。


我试过read()像上面那样使用和执行对整个文件的更改来读取文本文件。


import csv


filename = "origin.txt"

csv_file = 'replacements.csv'

conversion_dict = {}


# Create conversion dictionary

with open(csv_file, "r") as replace:

    reader = csv.reader(replace, delimiter=',')

    for rows in reader:

        conversion_dict.update({rows[0]:rows[1]})


#Replace values on text files based on conversion dict

with open(filename, "r") as fileobject:

    txt = str(fileobject.read())

    for keys, values, in conversion_dict.items():

        new_text = txt.replace(keys, values)

我还尝试将更新后的文本添加到列表中:


#Replace values on text files based on conversion dict

with open(filename, "r") as fileobject:

    txt = str(fileobject.read())

    for keys, values, in conversion_dict.items():

        new_text.append(txt.replace(keys, values))

然后,我尝试readlines()一次一行地用新值替换旧值:


# Replace values on text files based on conversion dict

with open(filename, "r") as reader:

    reader.readlines()

    type(reader)

    for line in reader:

        print(line)

        for keys, values, in conversion_dict.items():

            new_text.append(txt.replace(keys, values))

在进行故障排除时,我运行了一个测试,看看我的字典中的键和文件中的文本是否匹配:


for keys, values, in conversion_dict.items():

    if keys in txt:

        print("match")

    else:

        print("no match")

match除了第一行,我的输出在每一行都返回。我想通过一些修剪或其他东西我可以解决这个问题。但是,这证明存在匹配项,因此我的代码一定存在其他问题。


任何帮助表示赞赏。


暮色呼如
浏览 110回答 1
1回答

幕布斯7119047

来源.txt:oldVal9000,oldVal1,oldVal2,oldVal3,oldVal69测试.csv:oldVal1,newVal1oldVal2,newVal2oldVal3,newVal3oldVal4,newVal4import csvfilename = "origin.txt"csv_file = 'test.csv'conversion_dict = {}with open(csv_file, "r") as replace:    reader = csv.reader(replace, delimiter=',')    for rows in reader:        conversion_dict.update({rows[0]:rows[1]})f = open(filename,'r')txt = str(f.read())f.close()txt= txt.split(',')         #not sure what your origin.txt actually looks like, assuming comma seperated valuesfor i in range(len(txt)):    if txt[i] in conversion_dict:        txt[i] = conversion_dict[txt[i]]        with open(filename, "w") as outfile:    outfile.write(",".join(txt))修改后的origin.txt:oldVal9000,newVal4,newVal1,newVal3,oldVal69
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python