编程做一个记账本怎么做

时间:2025-03-05 10:18:51 明星趣事

要开发一个记账本程序,你可以选择使用不同的编程语言和工具,根据你的需求和熟悉程度来定制。下面我将提供一个基本的Python记账本程序的示例,以及一个简单的C++记账本程序的框架。

Python 记账本程序示例

```python

import csv

from datetime import datetime

class AccountBook:

def __init__(self, filename='account_book.csv'):

self.filename = filename

self.headers = ['日期', '类型', '金额', '备注']

初始化CSV文件

try:

with open(self.filename, 'x', newline='', encoding='utf-8') as f:

writer = csv.writer(f)

writer.writerow(self.headers)

except FileExistsError:

print(f"{self.filename} 已存在,请选择其他文件名或覆盖现有文件。")

def add_record(self, record_type, amount, description):

with open(self.filename, 'a', newline='', encoding='utf-8') as f:

writer = csv.writer(f)

writer.writerow([datetime.now().strftime('%Y-%m-%d'), record_type, amount, description])

def view_records(self):

try:

with open(self.filename, newline='', encoding='utf-8') as f:

reader = csv.DictReader(f)

for row in reader:

print(row)

except FileNotFoundError:

print(f"{self.filename} 不存在,请先创建。")

def calculate_totals(self):

try:

with open(self.filename, newline='', encoding='utf-8') as f:

reader = csv.DictReader(f)

income = 0

expense = 0

for row in reader:

if row['类型'] == '收入':

income += float(row['金额'])

elif row['类型'] == '支出':

expense += float(row['金额'])

return {'总收入': income, '总支出': expense}

except FileNotFoundError:

print(f"{self.filename} 不存在,请先创建。")

使用示例

account_book = AccountBook()

account_book.add_record('收入', 1000, '工资')

account_book.add_record('支出', 500, '食物')

account_book.view_records()

print(account_book.calculate_totals())

```

C++ 记账本程序框架