Requirements: Write a program to add goods, product information written in TXT file, in a two-dimensional dictionary form such as: {' millet ': {' Price ': ' 1999 Yuan ', ' Quantity ': 10}}
1. Add Items
#商品名称
#价格
#数量
2. View Products
3. Delete items
#输入商品名称
Requirements Analysis:
1. The conversion of strings and dictionaries can be done because the files are stored directly in the dictionary
2. Create a new dictionary, read the product information in the file as a string, and then move the string strongly to the dictionary
3. All operations are dictionary-oriented and keep the dictionary and file always "consistent"
Def Duqu ():
Shangpin_dic = {} #商品字典
Shangpin_str= ' #商品字符串
Shangpin_file = open (' Shangpin.txt ', ' w+ ') #商品文件
For i in Shangpin_file: #把文件中有的商品都写入字符串里
Shangpin_str = Shangpin_str + I
If shangpin_str! = ":
Shangpin_dic = eval (shangpin_str) #字符串转换成字典
Return Shangpin_dic
def start ():
A=duqu () #把文件中的商品都拿到字典里, a now is the dictionary of all goods, after the increase, delete, check are directly operating the dictionary
While 1 > 0:
xx = input (' Please enter your choice: 1, Add Item 2, view item 3, delete item, 4, exit \ n ')
if xx = = ' 1 ':
Add (a) #调用增加的方法, dictionary A is the argument here, and X in the method is the formal parameter
elif xx = = ' 2 ':
Chakan (a)
elif xx = = ' 3 ':
Shanchu (a)
elif xx = = ' 4 ':
Print (' Goodbye ')
Break
Else
Print (' You entered the wrong ')
def chakan (x):
If Len (x) > 0: #查看字典中的元素大于0, at least one item
For k in x:
Print ("Product Name:" +k+ ", Price:" +x.get (k). "Get (' prices ') +", Stock: "+x.get (k). Get (' stock ')) #输出字典中的商品
Else
Print ("No product") #字典中的元素不大于零, no items
def shanchu (x):
RM = input ("Please enter the name of the product you want to delete: \ n")
If X.get (rm, '-') = = '-':
Print ("The item you deleted does not exist")
Else
X.pop (RM)
Copytotxt (x)
def add (x): #x为形参
Add = input ("Please enter the product you want to add in the following format (product name _ price _ quantity, for example: Mi _1999 yuan _4) \ n")
Adds = Add.split ("_") #输入的商品分割后的list, for example: [' Millet ', ' 1999 Yuan ', 4]
If Len (adds)! = 3: #判断输入的格式, incorrect input format after splitting not three elements
Print ("Incorrect format for input")
Else
x[adds[0]]={' price ': adds[1], ' stock ': adds[2]} #在字典内增加输入的商品信息
Copytotxt (x) #写入文件
def copytotxt (x):
f = open (' Shangpin.txt ', ' W ')
F.write (str (x))
F.close ()
Print ("Operation succeeded")
Start ()
Python's Commodity Manipulation applet