所以我有一个文件,例如:
Book
Peter 500
George Peterson 300
Notebook
Lizzie 900
Jack 700整数是他们的奖品。我想读一下名字和字典的标书,但我被困在这里:
d = {}
with open('adat.txt') as f:
d = dict(x.rstrip().split(None, 1) for x in f)
for keys,values in d.items():
print(keys)
print(values)那么,如何正确地读取数据呢?
发布于 2014-04-08 20:53:28
您需要跳过“无效”行,如Book和Notebook。
d = {}
with open('adat.txt') as f:
for line in f:
words = line.split()
try:
price = int(words[-1])
name = ' '.join(words[:-1])
d[name] = price
except (ValueError, IndexError):
# line doesn't end in price (int() raised ValueError)
# or is empty (words[-1] raised IndexError)
pass
for key, value in d.items():
print(key)
print(value)https://stackoverflow.com/questions/22947809
复制相似问题