Hello, I am fairly new to Python and starting to get it. But I am having some difficulty with pickle. I am trying to get a account program to pickle user input and to save that in a data file and then reload said info and read as input for the program. I have finally got the pickle portion down, I am able to send the info I want but I cannot figure out the correct syntax to be able to keep adding to the file instead of simply overwriting what is in the data file. I want to be able to pickle info into set keys I guess, so that I can recall certain portions, vice versa. I am assuming it should be a list with a counter, that will keep adding to the file but not sure how to accomplish that. The code is below. I would appreciate any help. This is homework, but I am not trying to get anyone to just do it. I would really like to find out how to do this.
I have tried finding examples online but cannot find any code that does not totally confuse me but that also contains what I am trying to accomplish in it.
Thanks for any help!!!
import pickle as p
acctHist = 'acctHist.data'
class pettyAccount:
def __init__(self, initial, open='05 Sep 07'):
self.balance = initial
openDate = open
def deposit(self, amt, dDate='30 Oct 07'):
self.balance = self.balance + amt
self.date = dDate
def withdraw(self, amt, wDate='30 Oct 07'):
self.balance = self.balance - amt
self.date = wDate
def getbalance(self, gDate='30 Oct 07'):
self.date = gDate
return self.balance
def welcome(self):
prompt = input ('Welcome to the petty cash account: \
Enter 1 to Record a Deposit \
Enter 2 to Record a Withdrawal \
Enter 3 to Get the Balance')
if prompt == 1:
newDep = input ('Amount of deposit:')
newDate = raw_input ('Date of deposit:')
a.deposit(newDep)
f = file(acctHist, 'w')
pickFile = 'Deposit:',newDep, newDate
p.dump(pickFile, f)
f.close()
g = file(acctHist)
dTest = p.load(g) # A test so I could make sure that pickle was working
print dTest
print
print 'The new balance is $',a.getbalance(), 'on %s.' % newDate
return a.welcome()
elif prompt == 2:
newWith = input ('Amount of withdrawal:')
balance = a.getbalance()
if newWith > balance:
print 'Withdrawal exceeded account balance: $',balance, ' Reduce withdrawal amount.'
return a.welcome()
else:
newDate = raw_input ('Date of withdrawal:')
a.withdraw(newWith)
f = file(acctHist, 'w')
pickFile = 'Withdrawl:',newWith, newDate
p.dump(pickFile, f)
f.close()
g = file(acctHist)
wTest = p.load(g)
print wTest # A test so I could make sure that pickle was working
print
print 'The new balance is $',a.getbalance(), 'on %s.' % newDate
return a.welcome()
elif prompt == 3:
today = raw_input ("Enter today's date:")
print 'The current balance is $',a.getbalance(), 'on %s.' % today
return a.welcome()
else:
print 'Thank you, goodbye'
a = pettyAccount(1000)
a.welcome()