Create a file named virtual_library.py
and add the following code:
pythonCopy codeimport json
import os
class Book:
def __init__(self, title, author, year, isbn):
self.title = title
self.author = author
self.year = year
self.isbn = isbn
def to_dict(self):
return {
'title': self.title,
'author': self.author,
'year': self.year,
'isbn': self.isbn,
}
class VirtualLibrary:
def __init__(self, filename='library.json'):
self.filename = filename
self.books = self.load_books()
def load_books(self):
"""Load books from a JSON file."""
if os.path.exists(self.filename):
with open(self.filename, 'r') as file:
return [Book(**data) for data in json.load(file)]
return []
def save_books(self):
"""Save books to a JSON file."""
with open(self.filename, 'w') as file:
json.dump([book.to_dict() for book in self.books], file)
def add_book(self, title, author, year, isbn):
"""Add a new book to the library."""
new_book = Book(title, author, year, isbn)
self.books.append(new_book)
self.save_books()
print("Book added!")
def view_books(self):
"""View all books in the library."""
if not self.books:
print("No books available.")
return
print("\nBooks in the Library:")
for index, book in enumerate(self.books, start=1):
print(f"{index}. {book.title} by {book.author} ({book.year}) - ISBN: {book.isbn}")
print()
def search_books(self, search_term):
"""Search for books by title or author."""
results = [book for book in self.books if search_term.lower() in book.title.lower() or search_term.lower() in book.author.lower()]
if results:
print("\nSearch Results:")
for index, book in enumerate(results, start=1):
print(f"{index}. {book.title} by {book.author} ({book.year}) - ISBN: {book.isbn}")
else:
print("No books found matching that search term.")
print()
def run(self):
"""Run the virtual library application."""
while True:
print("Virtual Library")
print("1. Add Book")
print("2. View Books")
print("3. Search Books")
print("4. Exit")
choice = input("Choose an option (1-4): ")
if choice == '1':
title = input("Enter the book title: ")
author = input("Enter the author: ")
year = input("Enter the publication year: ")
isbn = input("Enter the ISBN: ")
self.add_book(title, author, year, isbn)
elif choice == '2':
self.view_books()
elif choice == '3':
search_term = input("Enter title or author to search: ")
self.search_books(search_term)
elif choice == '4':
print("Exiting the application.")
break
else:
print("Invalid choice. Please try again.")
def main():
library = VirtualLibrary()
library.run()
if __name__ == "__main__":
main()
Step 2: Running the Virtual Library Application
- Open your terminal (or command prompt).
- Navigate to the directory where you saved
virtual_library.py
. - Run the script using the command:bashCopy code
python virtual_library.py
How It Works
- Book Class: Represents a book with attributes like title, author, year, and ISBN.
- VirtualLibrary Class: Manages the collection of books, including loading from and saving to a JSON file.
- Functions:
- load_books: Loads existing books from the JSON file.
- save_books: Saves the current books back to the JSON file.
- add_book: Adds a new book to the library.
- view_books: Displays all stored books.
- search_books: Searches for books by title or author.
- User Interface: A simple command-line interface that allows users to interact with the library.
Leave a Reply