python 能成功运行出来的完整代码 可以直接复制运行 实现一个图书管理系统 要求: 用户和图书数据存入txt文本中,做一个永久存储
时间: 2024-04-09 11:34:02 浏览: 18
下面是一个完整的图书管理系统的示例代码,你可以直接复制运行:
```python
# 存储用户数据
def store_user_data(username, password):
with open('user_data.txt', 'a') as file:
file.write(f'{username},{password}\n')
# 存储图书数据
def store_book_data(book_id, title, author):
with open('book_data.txt', 'a') as file:
file.write(f'{book_id},{title},{author}\n')
# 查询所有用户
def query_all_users():
with open('user_data.txt', 'r') as file:
for line in file:
username, password = line.strip().split(',')
print(f'Username: {username}, Password: {password}')
# 查询所有图书
def query_all_books():
with open('book_data.txt', 'r') as file:
for line in file:
book_id, title, author = line.strip().split(',')
print(f'Book ID: {book_id}, Title: {title}, Author: {author}')
while True:
print('Welcome to the Library Management System!')
print('1. Add a new user')
print('2. Add a new book')
print('3. Query all users')
print('4. Query all books')
print('5. Exit')
choice = input('Please enter your choice: ')
if choice == '1':
username = input('Enter the username: ')
password = input('Enter the password: ')
store_user_data(username, password)
print('User added successfully!')
elif choice == '2':
book_id = input('Enter the book ID: ')
title = input('Enter the book title: ')
author = input('Enter the book author: ')
store_book_data(book_id, title, author)
print('Book added successfully!')
elif choice == '3':
query_all_users()
elif choice == '4':
query_all_books()
elif choice == '5':
print('Thank you for using the Library Management System!')
break
else:
print('Invalid choice. Please try again.')
```
这段代码实现了一个图书管理系统,通过用户输入选择不同的操作,包括添加用户、添加图书、查询所有用户、查询所有图书和退出系统。用户和图书数据都会永久存储在对应的txt文本文件中。你可以根据需要进行进一步的修改和完善。