问题:对xz.txt文件进行遍历的时候只能查找到最后一个字典
shop_list = []
while True:
id=int(input('输入商品编号:'))
name=input('输入商品名称:')
a={'id':id,'name':name}
shop_list.append(a)
b=input('继续添加?y/n')
if b=='y':
continue
else:
print('输入的产品信息为:'+str(shop_list)+'\t')
a=input('确实储存?')
if a=='y':
break
else:
shop_list=[]
if a=='y':
print('以保存')
else:
print('以清除')
break
break
def save(shop_list):
try:
c=open('xz.txt','a',encoding='utf-8')
except:
c=open('xz.txt','w',encoding='utf-8')
for iten in shop_list:
print(iten)
c.write(str(iten)+'\n')
c.close()
save(shop_list)
```python
def chioce():
go=[]
while True:
a=input('输入要加入购物车的商品:')
with open('xz.txt','r',encoding='utf-8')as c:
shop=c.readlines()
for item in shop:
print(item)
item = dict(eval(item))
#print(shop)
#print(item)
a=int(a)
if item['id']==a:
b=item['name']
print(b)
go.append(b)
break
else:
print('没有这个商品')
break
shop.append(a)
print('购物车里有',go)
if __name__ == '__main__':
chioce()

if item['id']==a:
b=item['name']
print(b)
go.append(b)
break
你这里都满足条件退出循环了,那就肯定值存进去一个了
你题目的解答代码如下:(如有帮助,望采纳!谢谢! 点击我这个回答右上方的【采纳】按钮)
shop_list = []
while True:
id=int(input('输入商品编号:'))
name=input('输入商品名称:')
a={'id':id,'name':name}
shop_list.append(a)
b=input('继续添加?y/n')
if b=='y':
continue
else:
print('输入的产品信息为:'+str(shop_list)+'\t')
a=input('确实储存?')
if a=='y':
break
else:
shop_list=[]
if a=='y':
print('以保存')
else:
print('以清除')
break
break
def save(shop_list):
try:
c=open('xz.txt','a',encoding='utf-8')
except:
c=open('xz.txt','w',encoding='utf-8')
for iten in shop_list:
print(iten)
c.write(str(iten)+'\n')
c.close()
save(shop_list)
def chioce():
go=[]
while True:
a=input('输入要加入购物车的商品:')
with open('xz.txt','r',encoding='utf-8')as c:
shop=c.readlines()
for item in shop:
print(item)
item = dict(eval(item))
#print(shop)
#print(item)
a=int(a)
# 下面代码要加一层缩进,放到for循环中
if item['id']==a:
b=item['name']
print(b)
go.append(b)
break
else:
print('没有这个商品')
break
shop.append(a)
print('购物车里有',go)
if __name__ == '__main__':
chioce()