python图书管理系统代码包括文件
时间: 2024-02-02 07:02:34 浏览: 56
以下是一个简单的Python图书管理系统的代码示例:
```
import os
import json
def load_data():
if os.path.exists("books.json"):
with open("books.json", "r") as f:
return json.load(f)
else:
return []
def save_data(books):
with open("books.json", "w") as f:
json.dump(books, f)
def add_book():
title = input("Enter book title: ")
author = input("Enter author name: ")
year = input("Enter publication year: ")
books = load_data()
books.append({"title": title, "author": author, "year": year})
save_data(books)
print("Book added successfully.")
def view_books():
books = load_data()
if books:
for book in books:
print(f"{book['title']} by {book['author']} ({book['year']})")
else:
print("No books found.")
def search_book():
title = input("Enter book title to search: ")
books = load_data()
found_books = []
for book in books:
if title.lower() in book["title"].lower():
found_books.append(book)
if found_books:
for book in found_books:
print(f"{book['title']} by {book['author']} ({book['year']})")
else:
print("No matching books found.")
while True:
print("\nWelcome to the Book Management System")
print("1. Add Book")
print("2. View Books")
print("3. Search Book")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
add_book()
elif choice == "2":
view_books()
elif choice == "3":
search_book()
elif choice == "4":
break
else:
print("Invalid choice. Please try again.")
```
此代码包括一个books.json文件,用于存储书籍数据。要使用此代码,请将其保存为.py文件并运行。
阅读全文