[英]ValueError: too many values to unpack (expected 2) errors
My code: 我的代码:
def dictest():
global my_glossary
# read all lines of the file
inFile = open("glossary.txt", "r")
inText = inFile.read()
inFile.close()
my_glossary = {}
# iterate through all lines, after removing the line-end character(s)
for line in inText.splitlines():
if line != '': # ignore empty lines
(key,value) = line.split(",")
my_glossary[key] = value
addToGlossary = entryNew.get()
addToGlossaryDef = outputNew.get()
my_glossary[addToGlossary] = addToGlossaryDef
# list all the dictionary entries
for k,v in my_glossary.items():
print('key:', k, ', value:', v)
My Output: 我的输出:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
return self.func(*args)
File "I:\School\Working Glossary.py", line 59, in MultiFunc
dictest()
File "I:\School\Working Glossary.py", line 14, in dictest
(key,value) = line.split(",")
ValueError: too many values to unpack (expected 2)
I am trying to accomplish making of a keywords glossary using a text file as storage. 我正在尝试使用文本文件作为存储来完成关键字词汇表的制作。 I keep running into this error which is causing the program to not work. 我不断遇到此错误,导致该程序无法正常工作。
My text file contents: 我的文本文件内容:
bug, this is a test
test, this is another test
testing,testing
123,12354
I think you want this: 我想你想要这个:
>>> line = "hello,world,foo,bar"
>>> (key, value) = line.split(",", 1)
>>> key
'hello'
>>> value
'world,foo,bar'
>>>
The change being: (key, value) = line.split(",", 1) 更改为:(键,值)= line.split(“,”,1)
Passing 1 as the second argument to split tells split to stop after it comes across 1 comma, passing the rest of the line to value. 将split作为第二个参数传递1告诉split在遇到1个逗号后停止,将行的其余部分传递给value。
str.split([sep[, maxsplit]]) (...) If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). str.split([sep [,maxsplit]])(...)如果指定了maxsplit,则最多完成maxsplit分割(因此,列表中最多包含maxsplit + 1个元素)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.