使用Python语言完成图书管理功能的开发,要求该功能至少包括:输出图书管理主菜单、添加图书信息、删除图书信息、修改图书别信息、显示所有图书信息。要求将图书类别存储到book.csv文件中,文件格式如下: 在添加图书的时候,要求定义类booktype2,定义readBookType()方法,实现从booktype.csv读取图书类别的方法。 实现过程 1. 定义函数(PrintBookMenu()):输出图书管理主菜单,输出样式如下:
时间: 2024-02-18 17:59:40 浏览: 114
python面向对象法实现图书管理系统
5星 · 资源好评率100%
下面是一个简单的 Python 代码实现,包括了输出图书管理主菜单、添加图书信息、删除图书信息、修改图书信息、显示所有图书信息等功能,并将图书信息存储到book.csv文件中,同时使用类booktype2定义了readBookType()方法,用于从booktype.csv文件中读取图书类别信息:
```python
import csv
class booktype2:
def __init__(self, type_id, type_name):
self.type_id = type_id
self.type_name = type_name
def readBookType():
bookTypes = []
with open("booktype.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
bookTypes.append(booktype2(row[0], row[1]))
return bookTypes
class book:
def __init__(self, book_id, book_name, book_type, book_price):
self.book_id = book_id
self.book_name = book_name
self.book_type = book_type
self.book_price = book_price
def print_menu():
print("图书管理系统")
print("1. 添加图书")
print("2. 删除图书")
print("3. 修改图书")
print("4. 显示所有图书")
print("0. 退出系统")
def add_book():
book_id = input("请输入图书编号:")
book_name = input("请输入图书名称:")
book_types = readBookType()
for book_type in book_types:
print(book_type.type_id, book_type.type_name)
book_type_id = input("请输入图书类别编号:")
book_price = input("请输入图书价格:")
with open("book.csv", "a", newline="") as file:
writer = csv.writer(file)
writer.writerow([book_id, book_name, book_type_id, book_price])
print("图书添加成功!")
def delete_book():
book_id = input("请输入要删除的图书编号:")
data = []
with open("book.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] != book_id:
data.append(row)
with open("book.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("图书删除成功!")
def modify_book():
book_id = input("请输入要修改的图书编号:")
data = []
with open("book.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
if row[0] == book_id:
book_name = input("请输入新的图书名称:")
book_types = readBookType()
for book_type in book_types:
print(book_type.type_id, book_type.type_name)
book_type_id = input("请输入新的图书类别编号:")
book_price = input("请输入新的图书价格:")
row[1] = book_name
row[2] = book_type_id
row[3] = book_price
data.append(row)
with open("book.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
print("图书修改成功!")
def show_all_book():
with open("book.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row[0], row[1], row[2], row[3])
if __name__ == "__main__":
while True:
print_menu()
choice = input("请选择操作:")
if choice == "1":
add_book()
elif choice == "2":
delete_book()
elif choice == "3":
modify_book()
elif choice == "4":
show_all_book()
elif choice == "0":
break
else:
print("输入有误,请重新输入!")
```
注意,上述代码中的book.csv和booktype.csv文件需要提前创建好,文件格式如下:
booktype.csv
```
编号,名称
1,文学
2,哲学
3,历史
4,地理
5,数学
6,物理
7,化学
8,生物
9,计算机
10,其他
```
book.csv
```
编号,名称,类别,价格
1,红楼梦,1,20.00
2,西游记,1,30.00
3,水浒传,1,25.00
4,三国演义,1,22.00
```
阅读全文