heya again guys - sorry for asking for help once again, but i think once i have my head round this, i'll sort myself out pretty well *python noob* :?:

the prac is to add an option to change the price of a listed item in a catalog - this ive completed with no probs at all.
But we also have to read & write to an external txt file - for whatever reason, i cant get this to work. It keeps wiping out my txt file (obviously im screwing up the write code somewhere????) anyway - the code with the correct 'change $' def is printed, to show where ive gone right
then the changes ive made to try & open a txt file is posted - to show where im going wrong.

After i get the txt read/write sorted, i also need to adjest it to let me add items/delete items etc - but ill be doing that myself - i just need some help as to where im going wrong at the stage im at. - im guessing i need to provide field headings (eg ItemID, name, price, stock) and the program uses the txt file to provide/save data.

correct code up to the 'change item $' point

def main(): 
    global catalog 

    loadCatalog() 
    while True: 
        pick = showMenu() 
        if pick == 0: 
            break 
        elif pick == 1: 
            sellItem() 
        elif pick == 2: 
            buyItem() 
        else: 
            print "Invalid selection" 
    saveCatalog() 

def showMenu(): 
    global catalog 

    while True: 
        print "Catalog:\n\t%6s %12s %8s %8s" % ( "ItemID", "Item", "Price", "Stock" ) 
        for k in catalog.keys(): 
            print "\t%6d %12s %8s %8d" % (k,catalog[k][0], str("$%0.2f" % catalog[k][1]), catalog[k][2]) 

        try: 
            pick = int(raw_input(''' 
Enter selection: 
0 - Quit 
1 - Sell Item 
2 - Buy Item
3 - Check Price

Selection : ''' )) 
        except: 
            print "Pick must be an integer\n" 
            continue 
        return pick 

def sellItem(): 
    global catalog 
    print "sellItem" 

    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            howMany = int(raw_input("How many? ")) 
            if 0 < howMany <= catalog[itemID][2]: 
                catalog[itemID][2] -= howMany 
                print "Price for %d %s is $%0.2f" % ( howMany, catalog[itemID][0],catalog[itemID][1]*howMany ) 
            else: 
                print "Can't sell %d %s" % ( howMany, catalog[itemID][0] ) 
        else: 
            print "Invalid itemID" 
    except: 
        print "Bad value entered" 
    print 

def buyItem(): 
    global catalog 
    print "buyItem" 
    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            howMany = int(raw_input("How many? ")) 
            if 0 < howMany: 
                catalog[itemID][2] += howMany 
            else: 
                print "Can't buy %d %s" % ( howMany, catalog[itemID][0] ) 
        else: 
            print "Invalid itemID" 
    except: 
        print "Bad value entered" 
    print 

def checkPrice(): 
    global catalog 
    print "checkPrice" 
    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            newPrice = float(raw_input("Enter new Price? ")) 
            if newPrice <0:
                 print "%d is a negative amount. Please enter a correct Price" % ( newPrice ) 
            else:       
                catalog[itemID][1]= newPrice
                print "You changed the price to %d for the %s " % (newPrice, catalog[itemID][0] )
        else:
            print "Invalid itemID" 
    except: 
        print "Bad value entered"
    saveCatalog()
    print 

def loadCatalog(): 
    global catalog 
    catalog = { 1:["Bread", 1.50, 10 ], 2:["Cheese", 5.00, 5], 3:["Apples", 2.50,12] } 

def saveCatalog(): 
    global catalog 
    pass 

if __name__ == "__main__": 
    main()

code changed to read/write to txt file - where am i screwing up?? - I keep getting the error: for k in catalog.keys():
AttributeError: 'file' object has no attribute 'keys'

def main():

    c=open("catalog.txt", "r")
    
    for line in c:
        fields = line.split(',')
        itemID = fields[0]
        name = fields[1]
        price = fields[2]
        stock = fields[3]

        d=open("catalog.txt","w")
        for item in catalog.values():
            count -= 1
        outputString = "%d %s %0.2f %d" % (itemID[0], name[1], price[2], stock[3])
        d.write(outputString)
        if count > 0:
            d.write("\n")
        d.close()

        catalog[itemID] = [name,price,stock]
 
    loadCatalog() 
    while True: 
        pick = showMenu() 
        if pick == 0: 
            break 
        elif pick == 1: 
            sellItem() 
        elif pick == 2: 
            buyItem()
        elif pick == 3: 
            checkPrice()
                   
        else: 
            print "Invalid selection" 
    saveCatalog() 

def showMenu(): 
    global catalog 

    while True: 
        print "Catalog:\n\t%6s %12s %8s %8s" % ( "ItemID", "Item", "Price", "Stock" ) 
        for k in catalog.keys(): 
            print "\t%6d %12s %8s %8d" % (k,catalog[k][0], str("$%0.2f" % catalog[k][1]), catalog[k][2]) 

        try: 
            pick = int(raw_input(''' 
Enter selection: 
0 - Quit 
1 - Sell Item 
2 - Buy Item
3 - Check Price

Selection : ''' )) 
        except: 
            print "Pick must be an integer\n" 
            continue 
        return pick 

def sellItem(): 
    global catalog 
    print "sellItem" 

    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            howMany = int(raw_input("How many? ")) 
            if 0 < howMany <= catalog[itemID][2]: 
                catalog[itemID][2] -= howMany 
                print "Price for %d %s is $%0.2f" % ( howMany, catalog[itemID][0],catalog[itemID][1]*howMany ) 
            else: 
                print "Can't sell %d %s" % ( howMany, catalog[itemID][0] ) 
        else: 
            print "Invalid itemID" 
    except: 
        print "Bad value entered"
    saveCatalog()
    print 

def buyItem(): 
    global catalog 
    print "buyItem" 
    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            howMany = int(raw_input("How many? ")) 
            if 0 < howMany: 
                catalog[itemID][2]= howMany
                print "You added %d %s to the Stock" % ( howMany, catalog[itemID][0] )
            else: 
                print "Can't buy %d %s" % ( howMany, catalog[itemID][0] ) 
        else: 
            print "Invalid itemID" 
    except: 
        print "Bad value entered"
    saveCatalog()
    print 

def checkPrice(): 
    global catalog 
    print "checkPrice" 
    try: 
        itemID = int(raw_input("Which item? ")) 
        if itemID in catalog.keys(): 
            newPrice = float(raw_input("Enter new Price? ")) 
            if newPrice <0:
                 print "%d is a negative amount. Please enter a correct Price" % ( newPrice ) 
            else:       
                catalog[itemID][1]= newPrice
                print "You changed the price to %d for the %s " % (newPrice, catalog[itemID][0] )
        else:
            print "Invalid itemID" 
    except: 
        print "Bad value entered"
    saveCatalog()
    print

def loadCatalog(): 
    global catalog 

def saveCatalog():
    print "All changes have been saved"
    global catalog 
    pass 

if __name__ == "__main__": 
    main()

raw_input("\n\npress ENTER to continue")

thanks v much for any hints as to where i need to change things

and just to add - i have tried putting the open read and write code down in the loadCatalog & saveCatalog defs - i still get the same error (plus one about catalog being undefined from memory ...)

It keeps clearing the text file because your passing the "w" to the open method.
"a" appends data to the end while keeping everything else untouched.

As for the data changing, why not use pickle?
It would be easier that way.

The best I can figure it, is to first read everything in the file and store it before opening to write. The change values in the stored read, and rewrite the entire thing when your done. If that makes any sense.

out lecturer doesnt like the pickle function ???? he made us skip that whole section of the textbook - go figure???

so should i list all the w functions in the saveCatalog def??

Keeping in mind I'm doing the same course(and assignment), I went in a different way with load in loadcatalog and save in savecatalog. Hope this helps.

#Loading and writing module

#load
inputfile = open('a2q3input.txt', 'r+')
lines = inputfile.readlines()
#create empty dictionary
catalog = {} 
#loop over lines to add to dictionary
for line in lines:
    line = line.lstrip('[')
    catalist = line.split( )
    #add elements to catalog dictionary
    catalog[int(catalist[0])] = [str(catalist[1]), float(catalist[2]), int(catalist[3])]        

print catalog

#Save
outputfile = open("a2q3output.txt", "w")
#loop over catalog keys
for k in catalog.keys():
    #Write line into output file
    outputfile.write("%d %s %s %d" % (k,catalog[k][0], str("%f" % catalog[k][1]), catalog[k][2])
#close output file
outputfile.close()
print "catalog saved"                     
raw_input('Press enter')

jvigar heh - ive only asked for help here once before - but ive browsed the threads often enough looking for examples of what i had in mind. Is a useful forum!

k, as i mentioned above, i suspected puting open, read & write in the loadCatalog & saveCatalog defs - just couldnt get it to work.

your code has ironed out some of my wrinkles - i now have to tidy up how the headings print, and get the entire list to reappear everytime i complete a choice .... then onto adding items.
Im not sure i have my head around dictionaries entirely - but ill be coding like mad for the rest of this week (around work & family) - so hopefuly the veil will start to lift soon

I had the same problem

give it 'a' permission instead of 'w' and it will not wipe the text from your text file

can you post catalog.txt file ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.