python写一个图书管理
时间: 2024-12-11 16:03:03 浏览: 9
Python编写图书管理系统是一个常见的编程练习,可以涉及到文件操作、数据结构(如列表、字典)以及简单的命令行交互。下面是一个简单的例子,创建一个Book类表示图书,并存储在一个名为books.txt的文本文件中:
```python
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
def save_book(book, filename="books.txt"):
with open(filename, "a") as f:
f.write(f"{book.title},{book.author},{book.year}\n")
def load_books(filename="books.txt"):
books_list = []
if os.path.exists(filename):
with open(filename, "r") as f:
for line in f:
title, author, year = line.strip().split(',')
books_list.append(Book(title, author, int(year)))
return books_list
# 示例
book1 = Book("Python Crash Course", "Eric Matthes", 2015)
save_book(book1)
books = load_books()
for book in books:
print(f"书名: {book.title}, 作者: {book.author}, 出版年份: {book.year}")
阅读全文