我不能用python将文件转换为字典
我试图将文件转换为字典,但出现错误我不能用python将文件转换为字典,python,dictionary,Python,Dictionary,我试图将文件转换为字典,但出现错误 def txt_to_dict(): dict = {} with open("GEO_human.gaf") as f: for line in f: (key, val) = line.split(":") dict[(key)] = val print dict txt_to_dict() 这是我的错误 键,val=line.split:ValueError
def txt_to_dict():
dict = {}
with open("GEO_human.gaf") as f:
for line in f:
(key, val) = line.split(":")
dict[(key)] = val
print dict
txt_to_dict()
这是我的错误
键,val=line.split:ValueError:需要多个值才能
打开
使用Json库:
将dict保存到文件中
with open("your_file") as f:
f.write(json.dumps(your_dict))
从文件加载dict
with open("your_file") as f:
d = json.load(f)
一行中可能不止一个“:”。 您可以尝试:
(key, val) = line.split(":", 1)
此代码在第一行“:”处拆分行。如果您将文件保存为类似于f.writejson.dumpsyour_dict.打开并读取:将您的_文件作为f:d=json.loadfAre打开,您确定每一行都像blah:yada吗?错误很明显,您的文件格式不正确显示GEO_human.gafcontent@Colin,不,不是,但正如我在下面提到的,我对python非常陌生,所以我不确定该怎么办。我尝试过,但仍然有相同的问题,但感谢您的帮助: