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:    ')
               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!


Edited by fheppell: mis spelt title

4 Years
Discussion Span
Last Post by Lucaci Andrew
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()
            # 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:
                    print 'Transaction processed, New Card Value = ' + value
                print 'Not enough money on card'
            # Error occurred while doing simple math (value probably bad)
            print 'Invalid total from ' + cardno + '.txt!'
    # 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..

Edited by chriswelborn: insert point clarified, used float for dollar amounts


Here, this might help you:

        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."
                value -= total
                with open (cardno+".txt", "w") as f: f.write(str(value))
    except IOError as e: print "Invalid card"

Edited by Lucaci Andrew

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.