How to write user input in python files?

1

I am a beginner in python and am doing an exercise that asks me to create a simple database in a .txt file that allows the user to register and query products and their values in reais, without having to access the file (open , but does not show on screen). Here is my code:

import os
try:
    op = open('C:/Users/Daniel/Desktop/database.txt','a')
except:
    op = open('C:/Users/Daniel/Desktop/database.txt', 'w')
dict = {}
while True:
    menu = int(input("Type 1 to register,2 to consult or 3 to remove: "))
    if menu == 1:
        #cadastrar produtos
        prod_cad = str(input("Type the product name: ")
        if [dict.has_key(prod_cad)]:
            print("This product is already registered.")
        else:
            val = float(input(" Type the price of product: "))
            op.write(dict[prod_cad]=val",")

My question is precisely in this last part that records the name and value of the product in the file. I have no idea how to send these values to the file and organize so that each tuple 'product': value (int) is separated by commas and kept accessible for later user query. I know I can not write like this:%% cos_de% because I would be sending the name of the variable and not the value. Thanks in advance for any help!

    
asked by anonymous 17.08.2017 / 02:26

2 answers

2

Try to run your code and probably will not, it has some syntax errors. Try to run the version below:

import os
f = open("products.txt", "w")
dict = {}
while True:
    pd = input('Type the product name ("End" for quit)')
    if pd.lower()=='end':
        f.close()
        break
    if pd in dict:
        print ('This product is already registered')
    else:
        pr = float(input(" Type the price of product: ")) 
        s = pd+','+str(pr)+'\n'
        dict[pd] = pr
        f.write(s)

Let's say you enter the values:

Productname    Price:
p1             10  
p2             20 
p3             30
End

If you have listed the file ( type on windows, cat on linux) you will see the following:

$ cat products.txt
p1,10.0
p2,20.0
p3,30.0
    
17.08.2017 / 03:21
1

I believe that in this case you can use .format :

produto = ("{} = {}").format(dict[prod_cad], val)
op.write(produto)

link

    
17.08.2017 / 02:41