I need to build a gift voucher section of my python cash register software
Here's the code I have so far

elif payment == '3':
            print "Scan or enter gift card"
            cardno = raw_input('Card Number:    ')
            try:
               with open(cardno, '.txt') as f: pass
               value = f.readline()
            except IOError as e:
               print 'Invalid number'

Just to clarify how my code works, when a gift card is created a text file called [card number].txt is created. I need to read the first line of this file, which contains the amount left on the gift card (eg 15.30). I need to check that this number is bigger than a variable called total, if it is take total away from the value of the gift card and over-write the file. If not, display error.

I have no idea where to go after the code I have written!

Thanks

line 6 should be inside the with block

import os # <-i put these at the top of script except for rare occasions
# make sure the file is there, could've entered bad card number
if os.path.isfile(os.path.join(cardno, '.txt')):
    with open(os.path.join(cardno, '.txt'), 'r') as f:
        value = f.readline()
        try:
            # value was read in as string, casting to float (you may need a better type)
            if total < float(value):
                total -= float(value) # total = total - float(value) for readability?
                # write new card value to file (overwrites old value)
                with open(cardno + '.txt', 'w') as fwrite:
                    f.write(str(total))
                    print 'Transaction processed, New Card Value = ' + value
            else:
                print 'Not enough money on card'
        except:
            # Error occurred while doing simple math (value probably bad)
            print 'Invalid total from ' + cardno + '.txt!'
else:
    # card file didn't exist, bad card number...
    print 'Card Number ' + cardno + ' Doesn't Exist!'

something along those lines i think, i haven't tested any of it. i started after the cardno was read by raw_input..

Here, this might help you:

    try:
        with open (cardno+".txt", "r") as f:
            try: value = float(f.readline())
            except ValueError as e: print "Empty card"
            if (value < total): print "Not enough money."
            else:
                value -= total
                with open (cardno+".txt", "w") as f: f.write(str(value))
    except IOError as e: print "Invalid card"
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.