Python可以用来做账,下面是一个简单的例子,展示了如何使用Python来记录收入和支出:
```python
from time import strftime
import pickle
def save_money(fname):
now_time = strftime('%Y-%m-%d')
try:
money = int(input('收入(元):'))
content = input('收入说明:')
except ValueError as e:
print('\033[31m输入错误:\033[0m', e)
return
else:
all_balance = int(pickle.load(open(fname, 'rb'))) + money
new_bill = [now_time, money, 0, all_balance, content]
with open(fname, 'wb') as fobj:
pickle.dump(new_bill, fobj)
print('操作成功')
def cost(fname):
now_time = strftime('%Y-%m-%d')
try:
money = int(input('支出(元):'))
content = input('支出说明:')
except ValueError as e:
print('\033[31m输入错误:\033[0m', e)
return
else:
with open(fname, 'rb') as fobj:
records = pickle.load(fobj)
old_balance = records[-1]
all_balance = old_balance - money
new_bill = [now_time, 0, money, all_balance, content]
records.append(new_bill)
with open(fname, 'wb') as fobj:
pickle.dump(records, fobj)
print('操作成功')
示例使用
filename = 'account.book'
if os.path.exists(filename):
os.remove(filename)
save_money(filename)
cost(filename)
这个脚本定义了两个函数:`save_money`用于记录收入,`cost`用于记录支出。它们都从用户那里获取金额和说明,然后将这些信息以二进制格式保存到`account.book`文件中。
请注意,这个脚本是一个简单的示例,实际应用中可能需要更复杂的逻辑来处理不同的收支类型、分类和报表生成等。此外,出于安全考虑,实际应用中不建议将财务数据以明文形式存储在文件中,而应该使用加密或其他安全措施来保护数据。