图书信息管理功能用Python语句,并将图书信息存储到book.csv
时间: 2024-03-01 15:55:43 浏览: 64
好的,以下是一个基本的图书信息管理功能的Python代码示例,可以将图书信息存储到book.csv文件中:
```
import csv
# 输出图书信息管理主菜单
def print_menu():
print("欢迎使用图书信息管理系统!")
print("1. 添加图书信息")
print("2. 删除图书信息")
print("3. 修改图书信息")
print("4. 显示所有图书信息")
print("0. 退出系统")
# 添加图书信息
def add_book():
book_list = []
book_name = input("请输入图书名称:")
book_author = input("请输入图书作者:")
book_price = input("请输入图书价格:")
book_dict = {"name": book_name, "author": book_author, "price": book_price}
book_list.append(book_dict)
with open("book.csv", "a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for book in book_list:
writer.writerow([book["name"], book["author"], book["price"]])
print("图书信息添加成功!")
# 删除图书信息
def del_book():
book_name = input("请输入要删除的图书名称:")
with open("book.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
book_list = list(reader)
with open("book.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for book in book_list:
if book[0] != book_name:
writer.writerow(book)
print("图书信息删除成功!")
# 修改图书信息
def modify_book():
book_name = input("请输入要修改的图书名称:")
with open("book.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
book_list = list(reader)
with open("book.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
for book in book_list:
if book[0] == book_name:
book_author = input("请输入修改后的图书作者:")
book_price = input("请输入修改后的图书价格:")
writer.writerow([book_name, book_author, book_price])
print("图书信息修改成功!")
else:
writer.writerow(book)
# 显示所有图书信息
def show_all_book():
with open("book.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
book_list = list(reader)
print("图书名称\t图书作者\t图书价格")
for book in book_list:
print(book[0] + "\t" + book[1] + "\t" + book[2])
# 主函数
def main():
while True:
print_menu()
choice = input("请输入您的选择:")
if choice == "1":
add_book()
elif choice == "2":
del_book()
elif choice == "3":
modify_book()
elif choice == "4":
show_all_book()
elif choice == "0":
print("感谢使用图书信息管理系统,再见!")
break
else:
print("输入有误,请重新输入!")
if __name__ == "__main__":
main()
```
这个程序可以通过运行Python文件来启动,将会输出一个图书信息管理的主菜单。在主菜单中可以选择添加、删除、修改或者显示所有图书信息。每次进行添加、删除、修改操作后,都会将最新的图书信息存储到book.csv文件中。您可以根据需要修改文件名、文件路径或者文件格式等信息。
阅读全文