【发布时间】:2017-06-18 11:52:56
【问题描述】:
基本上我想做的是让记事本列表显示在 python 中,这样用户就可以在不打开文件的情况下查看列表中的内容。我已经做到了。现在我想让用户输入他们想要的产品,然后保存它,然后打印出产品和价格。这是文本文件的样子:
000,67463528,50mm bolts,2.20
001,34512340,plain brackets,0.50
002,56756777,100mm bolts,0.20
003,90673412,l-shaped brackets,1.20
004,45378928,normal brackets,0.80
005,1638647,10mm bolts,0.10
006,14372841,plain brackets,1.29
007,29384754,200mm bolts,0.50
008,12345768,screwdriver,10.99
到目前为止,我可以在代码末尾添加产品,并且可以在某个行号处插入文本。我正在研究如何根据用户输入打印收据。我是 python 的新手,将其作为一种爱好来学习,任何帮助将不胜感激。谢谢!
这是python代码:
def search():
gtin = input("What is the GTIN code? ")
des = input("What is the name of the product? ")
price = input ("What is the price of the product? ")
position_str = input("What line do you want this inserted at? ")
print("This is the list now: ")
position = int(position_str)
with open("task2.txt", "r") as a_file:
data = a_file.readlines()
data.insert(position, "00" + position_str + "," + gtin + "," + des + "," + price + "\n")
data = "".join(data)
with open("task2.txt", "w") as a_file:
a_file.write(data)
input()
with open('task2.txt','r')as Task2:
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
for row in Task2:
row=row.strip()
eachItem=row.split(",")
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
print()
def add():
print("The data you put here will be added onto the end ")
gtin = input("What is the GTIN-8? ")
des = input("What is the description? ")
price = input("What is the price? ") #gets all the info they want to add
print("This is the list now: ")
with open("task2.txt","a") as a_file:
a_file.writelines(" ," + gtin + "," + des + "," + price + "\n")
a_file.close()
print("Product has been added")
with open('task2.txt','r')as Task2:
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
for row in Task2:
row=row.strip()
eachItem=row.split(",")
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
print()
def reciept():
print()
#this is the menu. this is where the user will make choices on what they do
def menu():
print("What would you like to do?")
with open('task2.txt','r')as Task2:
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format("\nNo.","GTIN-8","Item Name","Price"))
for row in Task2:
row=row.strip()
eachItem=row.split(",")
print('{0:<19} {1:<19} {2:<19} {3:<19}'.format(eachItem[0],eachItem[1],eachItem[2],eachItem[3]))
print()
print("1. Add a product onto a specific line number?")
print("2. Or add a product onto the end?")
print("3. Buy products and have them printed onto a reciept?")
choice=int(input("Which one?: "))
if choice==1:
search()
elif choice==2:
add()
elif choice==3:
reciept()
menu()
【问题讨论】:
-
如果这回答了您的问题,请接受答案。
标签: python file-handling