gpt4 book ai didi

python - 无法在 Python 中将第二行添加到字典中

转载 作者:行者123 更新时间:2023-11-30 22:46:24 25 4
gpt4 key购买 nike

我是 Python 脚本新手。有一个文件包含以下数据

Cascade.from = testvalue1 
cascade.from1 = testvalue2

以上上下文位于test.txt中。我编写了下面的代码,以便将其放入字典中并稍后获取它,代码如下

myvalue = {}
with open('test.txt', 'r') as myfile:
for line in myfile:
name, val = line.split('=')
myvalue[name] = str(val.strip())
print myvalue

运行上面的代码后,我只看到下面的数据{"cascade.from": "testvalue1"}它不会读取下一行,也不会添加到字典中。我的期望是:{"cascade.from": "testvalue1", "cascade.from1": "testvalue2"}。这样,当调用 myvalue["cascade.from1"] 时,它应该重新运行为 testvalue2谁能告诉我这里缺少什么吗?

上面只是函数中的一小部分,这是我的代码完整的东西

def readlocalfile():
os.chdir(sub_dir)
print ("prinintng current directory" + os.getcwd())
file = open(config_file,'r')
file_read = file.readlines()
myvars = {}
with open(config_file) as myfile:
for line in myfile:
name, var = line.split("=")
myvars[name] = str(var.strip())
print myvars
replace_val = myvars["cascade.from1"]
print ("the base value is "+ replace_val)

我在外部调用此函数,这会引发 KeyError

最佳答案

在循环中第一次,您尝试读取

myvars["cascade.from1"]

但是键 cascade.from1 在循环中第一次不存在,因为您只加载了第一行 Cascade.from (键cascade.from1 在循环中第二次创建)这就是为什么你会收到错误并且程序在行 replace_val= myvars["cascade.from1"] 处崩溃第一次。因此,print myvars 仅在循环中第一次运行,即您仅读取文件中的第一行时。

使用

replace_val= myvars["cascade.from1"]

您必须将其移到循环之外,因为 ince myvars 第一次在循环内不包含键 cascade.from1:

def readlocalfile():
os.chdir(sub_dir)
print ("prinintng current directory" + os.getcwd())
file=open(config_file,'r')
file_read=file.readlines()
myvars = {}
with open(config_file) as myfile:
for line in myfile:
name, var = line.split("=")
myvars[name] = str(var.strip())
print myvars
replace_val= myvars["cascade.from1"]
print ("the base value is "+ replace_val)

关于python - 无法在 Python 中将第二行添加到字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40885762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com