How to write user entries in python files?

Asked

Viewed 107 times

1

I’m a beginner in python and I’m doing an exercise that asks me to create a simple database in a file. txt that allows the user to register and consult products and their values in real, without the need to access the file (open, but not show on screen). Follows 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 doubt 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 comma and remains accessible for later user query. I know I can’t have you write like this:
op.write(dict['prod_cad']='val') because I would be sending the variable name and not the value. I would like to thank those who can help!

2 answers

3

Try running your code and you probably won’t be able to, there are some syntax errors. Try running 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 come in with the values:

Productname    Price:
p1             10  
p2             20 
p3             30
End

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

$ cat products.txt
p1,10.0
p2,20.0
p3,30.0

1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.