【发布时间】:2021-12-12 13:22:39
【问题描述】:
我正在尝试制作股票列表显示和编辑器项目。我试图让用户输入他们拥有的产品和库存数量,但它没有保存到 txt 文件中。
我哪里出错了,我没有收到任何错误。
def showStock(f):
print(f.read())
userDecide = input("""
To add items to your stock list please type 'ADD'
To remove items from your stock please type 'REMOVE'
To close application type 'CLOSE'
""")
if userDecide.lower() == 'add':
addStock(f)
elif userDecide.lower() == 'remove':
delStock()
elif userDecide.lower() == 'close':
print('Closing...')
exit()
else:
print('Response does not match criteria.')
def addStock(f):
item_add = input("""
Please enter the name of the item you wish to add.
: """)
f.write(item_add+': ')
quantityItem = input("""
Item added, please enter the current quantity for the item.
:
""")
f.write(quantityItem+'\n')
userDecide = input("""
Quantity added. All information has been saved. If you need to;
If you need to add more items type 'ADD'
If you need to delete items type 'REMOVE'
If you would like to exit application type 'CLOSE'
""")
if userDecide.lower() == 'add':
addStock(f)
elif userDecide.lower() == 'remove':
delStock()
elif userDecide.lower() == 'close':
print('Closing...')
exit()
else:
print('Response does not match criteria.')
exit()
with open('CurrentStock.txt', 'w+') as f:
print("""
=====================================================
Welcome to Max's stock project.
=====================================================
Current stock:
""")
showStock(f)
addStock(f)
【问题讨论】:
-
“添加库存”不是陷入无限循环吗?
-
@JeffUK 目前是的,但那是因为我还没有完成所有事情,不会再这样了
-
我删除了最后一行不需要的 addstock(f)。
-
我的意思是,如果您反复添加库存,您可能会因 max_recursion 错误而崩溃。似乎代码确实完全按照您的预期写入文件,问题是它没有从文件中读取。这是因为您使用 w+ 打开它会重置文件!试试 r+
-
已更改为 r+,现在可以使用了!!谢谢,我想我误解了 w+ 的表现!