我在名为的文本文件中包含以下数据'user_table.txt'
:
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
Charlotte - beutifulGIRL!
Christoper - chrisjohn
我正在尝试使用以下代码将此数据读入Python字典:
users = {}
with open("user_table.txt", 'r') as file:
for line in file:
line = line.strip()
# if there is no password
if '-' in line == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
print(users)
我收到以下错误:
ValueError: not enough values to unpack (expected 2, got 1)
这很可能是因为Billy的第一个实例没有'-'
拆分的原因。
如果是这样,解决此问题的最佳方法是什么?
谢谢!
您的条件是错误的,必须是:
for line in file:
line = line.strip()
# if there is no password
# if '-' not in line: <- another option
if ('-' in line) == False:
continue
# otherwise read into a dictionary
else:
key, value = line.split('-')
users[key] = value
要么
for line in file:
line = line.strip()
# if there is password
if '-' in line:
key, value = line.split('-')
users[key] = value
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句