E-book Reader Project (code) in Python

← Back to Projects

E-book Reader in Python

About the project: This is a Python project for a simple, command-line-based e-book reader. This project is a single, self-contained file that can read and display text files (.txt) page by page. It's a great foundation for building a more complex application.


This simple reader works by loading the entire text file into memory as a list of lines. It then uses a **`PAGE_SIZE`** constant to determine how many lines to display at once.

How to Use and Run the App

  1. Save the Code:Save the code above into a file named `ebook_reader.py`.
  2. Create a Text File:Create a sample text file (e.g., **`my_book.txt`**) in the same directory as the script. You can copy some text from a public domain book into it.
  3. Run the Script:Open your terminal or command prompt, navigate to the directory where you saved the files, and run the following command:
    
        python ebook_reader.py
        
  4. Enter the File Path: The program will prompt you to enter the path to your .txt file. For a file in the same directory, you can just type its name.

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE).




# ebook_reader.py

import os
import sys

# Define the number of lines to display per "page"
PAGE_SIZE = 25

def read_ebook(filepath):
    """
    Reads the content of a text file and returns a list of its lines.
    
    Args:
        filepath (str): The path to the text file.
    
    Returns:
        list: A list of strings, where each string is a line from the file.
              Returns None if the file cannot be opened.
    """
    if not os.path.exists(filepath):
        print(f"Error: The file '{filepath}' does not exist.")
        return None
    
    print(f"Opening and loading '{os.path.basename(filepath)}'...")
    try:
        with open(filepath, 'r', encoding='utf-8') as file:
            return file.readlines()
    except Exception as e:
        print(f"Error reading the file: {e}")
        return None

def display_page(lines, page_number):
    """
    Displays a single page of text from the list of lines.
    
    Args:
        lines (list): The list of all lines in the e-book.
        page_number (int): The current page number to display (1-based).
    """
    total_lines = len(lines)
    # Calculate the start and end indices for the current page
    start_index = (page_number - 1) * PAGE_SIZE
    end_index = start_index + PAGE_SIZE
    
    # Ensure the end index doesn't go beyond the total lines
    if end_index > total_lines:
        end_index = total_lines

    # Print the lines for the current page
    print("-" * 50)
    for line in lines[start_index:end_index]:
        # Strip leading/trailing whitespace from each line for cleaner output
        print(line.strip())
    print("-" * 50)
    
    # Display the current page and total pages
    total_pages = (total_lines + PAGE_SIZE - 1) // PAGE_SIZE
    print(f"Page {page_number}/{total_pages} - 'n' for next, 'p' for previous, 'q' to quit")

def run_reader():
    """
    The main loop for the e-book reader. It handles user input for navigation.
    """
    print("Welcome to the simple e-book reader.")
    filepath = input("Please enter the path to a .txt file: ").strip()
    
    lines = read_ebook(filepath)
    if lines is None:
        return # Exit if the file could not be read
        
    current_page = 1
    total_lines = len(lines)
    if total_lines == 0:
        print("The file is empty. Exiting.")
        return

    total_pages = (total_lines + PAGE_SIZE - 1) // PAGE_SIZE

    while True:
        display_page(lines, current_page)
        
        user_input = input("Enter your command: ").lower().strip()
        
        if user_input == 'n':
            if current_page < total_pages:
                current_page += 1
            else:
                print("You are already on the last page.")
        elif user_input == 'p':
            if current_page > 1:
                current_page -= 1
            else:
                print("You are already on the first page.")
        elif user_input == 'q':
            print("Thanks for using the reader. Goodbye!")
            break
        else:
            print("Invalid command. Please use 'n', 'p', or 'q'.")

if __name__ == "__main__":
    run_reader()
    


This project is a great starting point. You can add more if you like to explore adding more features, like a search function to find specific text within the e-book.



← Back to Projects