1. 程式人生 > >python-記賬小程式(80)

python-記賬小程式(80)

# 轉自https://www.jianshu.com/c/00c61372c46a網址
#1,記賬時手頭有一萬塊錢
#2,可以記錄花的錢,存的錢,以及收支明細

#wallet檔案記憶體總的錢數,餘額
#record檔案記憶體的是明細


import pickle
import os
import time

def cost(wallet,record):    #記錄花錢的函式
    amount = int(input('amount: ')) #輸入數字
    comment = input('comment: ')    #輸入
    date = time.strftime('%Y-%m-%d')
    with open(wallet,'rb') as fobj: #從檔案取總值減去amount
        balance = pickle.load(fobj) - amount
    with open(wallet,'wb') as fobj:
        pickle.dump(balance,fobj)   #將上面得到的值再寫入檔案內
    with open(record,'a') as fobj:  #向record對應檔案內追加各種資訊
        fobj.write(
            '%-15s%-8s%-8s%-8s%-20s\n' % (date,'',amount,balance,comment)
        )

def save(wallet,record):    #記錄存錢的函式
    amount = int(input('amount: '))
    comment = input('comment: ')
    date = time.strftime('%Y-%m-%d')
    with open(wallet,'rb') as fobj:
        balance = pickle.load(fobj) + amount
    with open(wallet,'wb') as fobj:
        pickle.dump(balance,fobj)
    with open(record,'a') as fobj:
        fobj.write(
            '%-15s%-8s%-8s%-8s%-20s\n' % (date,amount,'',balance,comment)
        )

def query(wallet,record):   #查詢收支明細的函式
    print('%-15s%-8s%-8s%-8s%-20s' % ('date','save','cost','balance','comment'))
    with open(record) as fobj:  #輸出明細
        for line in fobj:
            print(line,end='')
    with open(wallet,'rb') as fobj: #輸出餘額
        balance = pickle.load(fobj)
        print("Latest Balance: %d" % balance)

def show_menu():
    cmds = {'0':save,'1':cost,'2':query}
    prompt = """(0) save
(1) cost
(2) query
(3) exit
Please input your choice(0/1/2/3): """
    wallet = '/tmp/1wallet.data'
    record = '/tmp/1record.txt'
    if not os.path.exists(wallet):
        with open(wallet,'wb') as fobj: #如果/tmp/wallet.data不存在,則建立並寫入資料10000
            pickle.dump(10000,fobj)

    while True:
        try:
            choice = input(prompt).strip()[0]   #去除空格,選取第一個數字
        except ImportError:
            continue
        except (KeyboardInterrupt,EOFError):
            print()
            choice == '3'

        if choice not in '0123':
            print('Invalid input. Try again.')
            continue

        if choice == '3':
            break
        cmds[choice](wallet,record) #根據cmds字典和choice選擇執行上面定義的函式即查詢,花錢,存錢

if __name__ == '__main__':
    show_menu()