我正在尝试在文本文件中更改多个十六进制值。我制作了一个CSV,其中一列具有原始值,而另一列具有新值。
我的目标是编写一个简单的Python脚本,以便根据第一列在文本文件中查找旧值,并在第二列中将它们替换为新值。
我正在尝试使用字典来简化通过循环CSV创建的replace()
。构建它非常容易,但是使用它来执行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
。我认为可以进行一些修整或解决某些问题。但是,这证明存在匹配项,因此我的代码肯定还有其他问题。
感谢您的帮助。
答案 0 :(得分:0)
origin.txt:
oldVal9000,oldVal1,oldVal2,oldVal3,oldVal69
test.csv:
oldVal1,newVal1
oldVal2,newVal2
oldVal3,newVal3
oldVal4,newVal4
import csv
filename = "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 values
for 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