- 帖子
- 7
- 精华
- 0
- 积分
- 52
- 阅读权限
- 20
- 注册时间
- 2020-10-14
- 最后登录
- 2020-11-2
|
crossin先生 发表于 2016-8-19 11:06
可以的
crossin先生,请问这个记账本哪里需要改进吗?- import os
- import datetime
- import re
- class Account():
- def __init__(self):
- # 数据存储的文件路径
- self.file_name = "balance.txt"
- self.file_path = os.path.join(os.getcwd(), self.file_name)
- # 判断是否是首次记账,若否,则读出文件中的余额balance;若是,余额为0
- try:
- with open(self.file_path,"r", encoding="utf-8") as obj:
- balance_string = obj.readline().strip("\n")
- self.balance = eval(balance_string)["balance"]
- self.is_first = 0
- except FileNotFoundError as e:
- self.balance = 0
- self.is_first = 1
- def keep_accounts(self,item,money):
- '''记账'''
- with open(self.file_path, "a", encoding = "utf-8") as obj:
- time = str(datetime.date.today())
- line = time + " " + money + " " + item + "\n"
- obj.write(line)
- self.balance += float(money)
- def check_the_balance(self):
- '''查询余额'''
- print(self.balance)
- def check_the_details(self):
- '''查询账单详情'''
- try:
- with open(self.file_path, "r", encoding = "utf-8") as obj:
- details_list = obj.readlines()
- for one in details_list:
- if one.startswith("{"):
- continue
- print(one)
- except FileNotFoundError as e:
- print("尚未有收支记录!")
- if __name__ == "__main__":
- account = Account()
- while True:
- choice = input("选择操作:\n\t1、记账\n\t2、查余额\n\t3、收支明细\n").strip()
- if choice == "1":
- money = input("金额: ").strip()
- item = input("名目: ").strip()
- account.keep_accounts(item,money)
- elif choice == "2":
- account.check_the_balance()
- elif choice == "3":
- account.check_the_details()
- elif choice == "leave":
- break
- with open(account.file_path,"r+", encoding ="utf-8") as obj:
- data = obj.read()
- # 若非首次记账,将新的余额替换旧的余额
- if account.is_first == 0:
- new_balance_string = '{{"balance":{}}}'.format(str(account.balance))
- data = re.sub(r'{"balance":.*?}',new_balance_string,data)
- # 若是首次记账,在文件头部记录每次记账结束后的余额
- else:
- new_balance_string = '{{"balance":{}}}\n'.format(str(account.balance))
- data = new_balance_string + data
- obj.seek(0)
- obj.write(data)
复制代码 |
|