Python语言上面的商品信息可以循环的持有成文件中,在另一个文件中可以集中打印。
时间: 2024-03-25 16:38:00 浏览: 22
是的,可以使用Python语言来实现将商品信息持久存入文件,然后在另一个文件中读取并打印出来的功能。以下是一个简单的示例代码:
```python
# 商品信息写入文件
def write_to_file(product_name, price, quantity):
with open('products.txt', 'a') as f:
f.write(f"{product_name}\t{price}\t{quantity}\n")
# 商品信息读取并打印
def print_products():
print("商品名称\t商品单价\t购买数量\t金额小计")
with open('products.txt', 'r') as f:
for line in f:
product_name, price, quantity = line.strip().split('\t')
subtotal = float(price) * int(quantity)
print(f"{product_name}\t\t{price}\t\t{quantity}\t\t{subtotal}")
# 主程序
while True:
product_name = input("请输入购买的商品名称:【】")
price = input("请输入购买的商品单价:【】")
quantity = input("请输入购买的商品数量:【】")
write_to_file(product_name, price, quantity)
is_continue = input("是否继续结账下一种商品(yes/no):【】")
if is_continue.lower() == 'no':
break
print_products()
```
在这个示例代码中,首先定义了两个函数,一个用于将商品信息写入文件,另一个用于从文件中读取并打印商品信息。在主程序中,通过循环不断地询问用户要购买的商品信息,并将其写入文件。当用户不再需要购买商品时,程序会调用 `print_products()` 函数来读取并打印所有商品信息。
注意,这个示例代码并没有对用户的输入进行任何错误处理和验证,实际使用时需要根据具体情况进行完善。