我正在尝试更改文本文件中的几个十六进制值。我制作了一个 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除了第一行,我的输出在每一行都返回。我想通过一些修剪或其他东西我可以解决这个问题。但是,这证明存在匹配项,因此我的代码一定存在其他问题。
任何帮助表示赞赏。
幕布斯7119047
相关分类