Author: saqibkhan

  • Online Quiz and Exam Platform

    Requirements

    • Python 3.x
    • Flask
    • SQLite (for a simple database)
    • HTML/CSS/JavaScript (for the frontend)

    Step 1: Setting Up Your Environment

    First, ensure you have Flask installed. You can do this using pip:

    pip install Flask
    

    Step 2: Create the Flask App

    Create a directory for your project and inside it, create a file named app.py.

    # app.py
    from flask import Flask, render_template, request, redirect, url_for, session
    from flask_sqlalchemy import SQLAlchemy
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'your_secret_key'
    app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///quizzes.db'
    db = SQLAlchemy(app)
    
    # Models
    class Quiz(db.Model):
    
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100), nullable=False)
    class Question(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    quiz_id = db.Column(db.Integer, db.ForeignKey('quiz.id'), nullable=False)
    question_text = db.Column(db.String(200), nullable=False)
    options = db.Column(db.String(500), nullable=False)
    answer = db.Column(db.String(200), nullable=False)
    # Routes @app.route('/') def index():
    quizzes = Quiz.query.all()
    return render_template('index.html', quizzes=quizzes)
    @app.route('/quiz/<int:quiz_id>', methods=['GET', 'POST']) def quiz(quiz_id):
    if request.method == 'POST':
        # Handle quiz submission
        return redirect(url_for('results'))
    quiz = Quiz.query.get_or_404(quiz_id)
    questions = Question.query.filter_by(quiz_id=quiz_id).all()
    return render_template('quiz.html', quiz=quiz, questions=questions)
    @app.route('/results') def results():
    return "Results page"
    if __name__ == '__main__':
    db.create_all()
    app.run(debug=True)

    Step 3: Create HTML Templates

    Create a folder named templates in the same directory as your app.py. Inside this folder, create two HTML files: index.html and quiz.html.

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>Quizzes&lt;/title>
    </head> <body>
    &lt;h1>Available Quizzes&lt;/h1>
    &lt;ul>
        {% for quiz in quizzes %}
        &lt;li>&lt;a href="{{ url_for('quiz', quiz_id=quiz.id) }}">{{ quiz.title }}&lt;/a>&lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    quiz.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;title>{{ quiz.title }}&lt;/title>
    </head> <body>
    &lt;h1>{{ quiz.title }}&lt;/h1>
    &lt;form method="POST">
        {% for question in questions %}
        &lt;div>
            &lt;p>{{ question.question_text }}&lt;/p>
            {% for option in question.options.split(',') %}
            &lt;label>
                &lt;input type="radio" name="question_{{ question.id }}" value="{{ option }}">
                {{ option }}
            &lt;/label>&lt;br>
            {% endfor %}
        &lt;/div>
        {% endfor %}
        &lt;button type="submit">Submit&lt;/button>
    &lt;/form>
    </body> </html>

    Step 4: Populate the Database

    You can use a Python shell or create a separate script to add quizzes and questions to your database. For example:

    from app import db, Quiz, Question
    
    # Create quizzes and questions
    db.create_all()
    
    quiz1 = Quiz(title='Python Basics')
    db.session.add(quiz1)
    db.session.commit()
    
    question1 = Question(quiz_id=1, question_text='What is the output of 2 + 2?', options='3,4,5,6', answer='4')
    db.session.add(question1)
    db.session.commit()
    

    Step 5: Run Your Application

    Now you can run your Flask application:

    python app.py
    

    Step 6: Access the App

    Open your browser and navigate to http://127.0.0.1:5000/. You should see your quiz index page.

    Future Enhancements

    • User authentication (login/signup)
    • Score tracking
    • Timer for quizzes
    • Admin interface for quiz management
    • Frontend improvements with frameworks like React or Vue.js
  • Pet Adoption Platform

    Project Structure

    pet_adoption/
    │
    ├── app.py                # Main application file
    ├── templates/            # HTML templates
    │   ├── index.html
    │   ├── add_pet.html
    │   └── pet_details.html
    ├── static/               # Static files (CSS, JS, images)
    │   └── styles.css
    └── pets.db               # SQLite database
    

    Step 1: Set Up the Environment

    1. Install Flask:bashCopy codepip install Flask
    2. Set up SQLite (it usually comes with Python, but you can install it if necessary):bashCopy codepip install sqlite3

    Step 2: Create the Database

    Create a file named database.py to set up the SQLite database:

    import sqlite3
    
    def init_db():
    
    conn = sqlite3.connect('pets.db')
    c = conn.cursor()
    c.execute('''
        CREATE TABLE IF NOT EXISTS pets (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            name TEXT NOT NULL,
            breed TEXT NOT NULL,
            age INTEGER NOT NULL,
            description TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()
    if __name__ == '__main__':
    init_db()

    Run this file once to create the database.

    Step 3: Create the Main Application

    Create a file named app.py:

    from flask import Flask, render_template, request, redirect
    import sqlite3
    
    app = Flask(__name__)
    
    # Database helper functions
    def get_db_connection():
    
    conn = sqlite3.connect('pets.db')
    conn.row_factory = sqlite3.Row
    return conn
    @app.route('/') def index():
    conn = get_db_connection()
    pets = conn.execute('SELECT * FROM pets').fetchall()
    conn.close()
    return render_template('index.html', pets=pets)
    @app.route('/add', methods=('GET', 'POST')) def add_pet():
    if request.method == 'POST':
        name = request.form&#91;'name']
        breed = request.form&#91;'breed']
        age = request.form&#91;'age']
        description = request.form&#91;'description']
        conn = get_db_connection()
        conn.execute('INSERT INTO pets (name, breed, age, description) VALUES (?, ?, ?, ?)',
                     (name, breed, age, description))
        conn.commit()
        conn.close()
        return redirect('/')
    
    return render_template('add_pet.html')
    @app.route('/pet/<int:pet_id>') def pet_details(pet_id):
    conn = get_db_connection()
    pet = conn.execute('SELECT * FROM pets WHERE id = ?', (pet_id,)).fetchone()
    conn.close()
    return render_template('pet_details.html', pet=pet)
    if __name__ == '__main__':
    app.run(debug=True)

    Step 4: Create HTML Templates

    1. templates/index.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
    &lt;title>Pet Adoption&lt;/title>
    </head> <body>
    &lt;h1>Pet Adoption Platform&lt;/h1>
    &lt;a href="/add">Add a Pet&lt;/a>
    &lt;h2>Available Pets&lt;/h2>
    &lt;ul>
        {% for pet in pets %}
            &lt;li>
                &lt;a href="{{ url_for('pet_details', pet_id=pet&#91;'id']) }}">{{ pet&#91;'name'] }} ({{ pet&#91;'breed'] }})&lt;/a>
            &lt;/li>
        {% endfor %}
    &lt;/ul>
    </body> </html>

    2. templates/add_pet.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Add a Pet&lt;/title>
    </head> <body>
    &lt;h1>Add a Pet&lt;/h1>
    &lt;form method="post">
        &lt;label>Name:&lt;/label>&lt;br>
        &lt;input type="text" name="name" required>&lt;br>
        &lt;label>Breed:&lt;/label>&lt;br>
        &lt;input type="text" name="breed" required>&lt;br>
        &lt;label>Age:&lt;/label>&lt;br>
        &lt;input type="number" name="age" required>&lt;br>
        &lt;label>Description:&lt;/label>&lt;br>
        &lt;textarea name="description" required>&lt;/textarea>&lt;br>
        &lt;input type="submit" value="Add Pet">
    &lt;/form>
    </body> </html>

    3. templates/pet_details.html:

    <!doctype html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>{{ pet&#91;'name'] }}&lt;/title>
    </head> <body>
    &lt;h1>{{ pet&#91;'name'] }}&lt;/h1>
    &lt;p>Breed: {{ pet&#91;'breed'] }}&lt;/p>
    &lt;p>Age: {{ pet&#91;'age'] }} years&lt;/p>
    &lt;p>Description: {{ pet&#91;'description'] }}&lt;/p>
    &lt;a href="/">Back to Home&lt;/a>
    </body> </html>

    Step 5: Create a CSS File

    Create a file named static/styles.css for basic styling:

    body {
    
    font-family: Arial, sans-serif;
    margin: 20px;
    } h1 {
    color: #333;
    } a {
    text-decoration: none;
    color: blue;
    } ul {
    list-style-type: none;
    padding: 0;
    }

    Step 6: Run the Application

    1. Initialize the database:bashCopy codepython database.py
    2. Run the Flask app:
    python app.py
    1. Open your browser and go to http://127.0.0.1:5000/.
  • Directories

    Directories in Python

    In Python, directories, commonly known as folders in operating systems, are locations on the filesystem used to store files and other directories. They serve as a way to group and manage files hierarchically.

    Python provides several modules, primarily os and os.path, along with shutil, that allows you to perform various operations on directories.

    These operations include creating new directories, navigating through existing directories, listing directory contents, changing the current working directory, and removing directories.

    Checking if a Directory Exists

    Before performing operations on a directory, you often need to check if it exists. We can check if a directory exists or not using the os.path.exists() function in Python.

    This function accepts a single argument, which is a string representing a path in the filesystem. This argument can be −

    • Relative path − A path relative to the current working directory.
    • Absolute path − A complete path starting from the root directory.

    Example

    In this example, we check whether the given directory path exists using the os.path.exists() function −

    import os
    
    directory_path ="D:\\Test\\MyFolder\\"if os.path.exists(directory_path):print(f"The directory '{directory_path}' exists.")else:print(f"The directory '{directory_path}' does not exist.")

    Following is the output of the above code −

    The directory 'D:\\Test\\MyFolder\\' exists.
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Creating a Directory

    You create a new directory in Python using the os.makedirs() function. This function creates intermediate directories if they do not exist.

    The os.makedirs() function accepts a “path” you want to create as an argument. It optionally accepts a “mode” argument that specifies the permissions o set for the newly created directories. It is an integer, represented in octal format (e.g., 0o755). If not specified, the default permissions are used based on your system’s umask.

    Example

    In the following example, we are creating a new directory using the os.makedirs() function −

    Open Compiler

    import os
    
    new_directory ="new_dir.txt"try:
       os.makedirs(new_directory)print(f"Directory '{new_directory}' created successfully.")except OSError as e:print(f"Error: Failed to create directory '{new_directory}'. {e}")

    After executing the above code, we get the following output −

    Directory 'new_dir.txt' created successfully.
    

    The mkdir() Method

    You can use the mkdir() method of the os module to create directories in the current directory. You need to supply an argument to this method, which contains the name of the directory to be created.

    Following is the syntax of the mkdir() method in Python −

    os.mkdir("newdir")

    Example

    Following is an example to create a directory test in the current directory −

    Open Compiler

    import os
    
    # Create a directory "test"
    os.mkdir("test")print("Directory created successfully")

    The result obtained is as shown below −

    Directory created successfully
    

    Get Current Working Directory

    To retrieve the current working directory in Python, you can use the os.getcwd() function. This function returns a string representing the current working directory where the Python script is executing.

    Syntax

    Following is the basic syntax of the getcwd() function in Python −

    os.getcwd()

    Example

    Following is an example to display the current working directory using the getcwd() function −

    Open Compiler

    import os
    
    current_directory = os.getcwd()print(f"Current working directory: {current_directory}")

    We get the output as follows −

    Current working directory: /home/cg/root/667ba7570a5b7
    

    Listing Files and Directories

    You can list the contents of a directory using the os.listdir() function. This function returns a list of all files and directories within the specified directory path.

    Example

    In the example below, we are listing the contents of the specified directory path using the listdir() function −

    import os
    
    directory_path =r"D:\MyFolder\Pictures"try:
       contents = os.listdir(directory_path)print(f"Contents of '{directory_path}':")for item in contents:print(item)except OSError as e:print(f"Error: Failed to list contents of directory '{directory_path}'. {e}")

    Output of the above code is as shown below −

    Contents of 'D:\MyFolder\Pictures':
    Camera Roll
    desktop.ini
    Saved Pictures
    Screenshots
    

    Changing the Current Working Directory

    You can change the current directory using the chdir() method. This method takes an argument, which is the name of the directory that you want to make the current directory.

    Syntax

    Following is the syntax of the chdir() method in Python −

    os.chdir("newdir")

    Example

    Following is an example to change the current directory to Desktop using the chdir() method −

    import os
    
    new_directory =r"D:\MyFolder\Pictures"try:
    
    os.chdir(new_directory)print(f"Current working directory changed to '{new_directory}'.")except OSError as e:print(f"Error: Failed to change working directory to '{new_directory}'. {e}")</code></pre>

    We get the output as shown below −

    Current working directory changed to 'D:\MyFolder\Pictures'.
    

    Removing a Directory

    You can remove an empty directory in Python using the os.rmdir() method. If the directory contains files or other directories, you can use shutil.rmtree() method to delete it recursively.

    Syntax

    Following is the basic syntax to delete a directory in Python −

    os.rmdir(directory_path)# or
    shutil.rmtree(directory_path)

    Example

    In the following example, we remove an empty directory using the os.rmdir() method −

    import os
    directory_path =r"D:\MyFolder\new_dir"try:
       os.rmdir(directory_path)print(f"Directory '{directory_path}' successfully removed.")except OSError as e:print(f"Error: Failed to remove directory '{directory_path}'. {e}")

    It will produce the following output −

    Directory 'D:\MyFolder\new_dir' successfully removed.
  • Travel Planner

    Simple Travel Planner in Python

    class TravelPlanner:
    
    def __init__(self):
        self.destinations = {}
    
    def add_destination(self, name, activities):
        self.destinations&#91;name] = activities
    
    def view_destinations(self):
        print("Available Destinations:")
        for destination in self.destinations:
            print(f"- {destination}")
    def create_itinerary(self, destination, budget):
        if destination not in self.destinations:
            print("Destination not found.")
            return
        
        activities = self.destinations&#91;destination]
        itinerary = &#91;]
        
        print(f"\nCreating itinerary for {destination} with a budget of ${budget}:")
        
        for activity, cost in activities.items():
            if cost &lt;= budget:
                itinerary.append(activity)
                budget -= cost
                print(f"Added: {activity} (${cost})")
        
        if not itinerary:
            print("No activities fit within the budget.")
        else:
            print("\nFinal Itinerary:")
            for item in itinerary:
                print(f"- {item}")
    # Example Usage if __name__ == "__main__":
    planner = TravelPlanner()
    
    # Adding destinations and their activities
    planner.add_destination("Paris", {
        "Eiffel Tower Visit": 25,
        "Louvre Museum": 15,
        "Seine River Cruise": 30,
        "Notre Dame Cathedral": 0,
        "Montmartre Tour": 10
    })
    
    planner.add_destination("New York", {
        "Statue of Liberty": 20,
        "Broadway Show": 100,
        "Central Park": 0,
        "Museum of Modern Art": 25,
        "Brooklyn Bridge Walk": 0
    })
    
    # Viewing available destinations
    planner.view_destinations()
    
    # Creating an itinerary
    destination = input("\nEnter your destination: ")
    budget = int(input("Enter your budget: "))
    
    planner.create_itinerary(destination, budget)

    How to Use the Code

    1. Add Destinations: You can add destinations and their associated activities with costs.
    2. View Destinations: The program displays all available destinations.
    3. Create Itinerary: Enter a destination and budget to generate a list of activities that fit within your budget.

    Running the Code

    You can run this code in any Python environment. Just copy and paste it into a .py file or directly into a Python interpreter.

    Next Steps

    • Expand Activities: Include more detailed activity descriptions, timings, etc.
    • User Profiles: Allow users to save and load their travel preferences.
    • Web Integration: Create a web app using frameworks like Flask or Django for a more user-friendly interface.
  • Renaming and Deleting Files

    Renaming and Deleting Files in Python

    In Python, you can rename and delete files using built-in functions from the os module. These operations are important when managing files within a file system. In this tutorial, we will explore how to perform these actions step-by-step.

    Renaming Files in Python

    To rename a file in Python, you can use the os.rename() function. This function takes two arguments: the current filename and the new filename.

    Syntax

    Following is the basic syntax of the rename() function in Python −

    os.rename(current_file_name, new_file_name)

    Parameters

    Following are the parameters accepted by this function −

    • current_file_name − It is the current name of the file you want to rename.
    • new_file_name − It is the new name you want to assign to the file.

    Example

    Following is an example to rename an existing file “oldfile.txt” to “newfile.txt” using the rename() function −

    import os
    
    # Current file name
    current_name ="oldfile.txt"# New file name
    new_name ="newfile.txt"# Rename the file
    os.rename(current_name, new_name)print(f"File '{current_name}' renamed to '{new_name}' successfully.")

    Following is the output of the above code −

    File 'oldfile.txt' renamed to 'newfile.txt' successfully.
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Deleting Files in Python

    You can delete a file in Python using the os.remove() function. This function deletes a file specified by its filename.

    Syntax

    Following is the basic syntax of the remove() function in Python −

    os.remove(file_name)

    Parameters

    This function accepts the name of the file as a parameter which needs to be deleted.

    Example

    Following is an example to delete an existing file “file_to_delete.txt” using the remove() function −

    import os
    
    # File to be deleted
    file_to_delete ="file_to_delete.txt"# Delete the file
    os.remove(file_to_delete)print(f"File '{file_to_delete}' deleted successfully.")

    After executing the above code, we get the following output −

    File 'file_to_delete.txt' deleted successfully.
  • Custom URL Shortener

    Prerequisites

    Make sure you have Python installed, along with Flask and SQLite. You can install Flask via pip:

    pip install Flask
    

    Step 1: Set Up the Project Structure

    Create a directory for your project, for example, url_shortener. Inside this directory, create the following files:

    • app.py
    • database.db (this will be created automatically)
    • templates/
      • index.html
      • result.html

    Step 2: Create the Flask App (app.py)

    Here’s a simple Flask app to handle URL shortening:

    from flask import Flask, request, redirect, render_template
    import sqlite3
    import string
    import random
    
    app = Flask(__name__)
    
    # Database setup
    def init_db():
    
    with sqlite3.connect('database.db') as conn:
        conn.execute('''
            CREATE TABLE IF NOT EXISTS urls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                short_url TEXT UNIQUE,
                original_url TEXT NOT NULL
            )
        ''')
    conn.close()
    # Generate a random string def generate_short_url(length=6):
    characters = string.ascii_letters + string.digits
    return ''.join(random.choice(characters) for _ in range(length))
    # Route for the homepage @app.route('/') def index():
    return render_template('index.html')
    # Route to shorten the URL @app.route('/shorten', methods=['POST']) def shorten():
    original_url = request.form&#91;'url']
    short_url = generate_short_url()
    with sqlite3.connect('database.db') as conn:
        conn.execute('INSERT INTO urls (short_url, original_url) VALUES (?, ?)', (short_url, original_url))
    conn.close()
    return render_template('result.html', short_url=short_url)
    # Route to redirect to the original URL @app.route('/<short_url>') def redirect_to_url(short_url):
    with sqlite3.connect('database.db') as conn:
        cursor = conn.execute('SELECT original_url FROM urls WHERE short_url = ?', (short_url,))
        row = cursor.fetchone()
    conn.close()
    if row:
        return redirect(row&#91;0])
    else:
        return 'URL not found', 404
    if __name__ == '__main__':
    init_db()
    app.run(debug=True)

    Step 3: Create the HTML Templates

    templates/index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>URL Shortener&lt;/title>
    </head> <body>
    &lt;h1>URL Shortener&lt;/h1>
    &lt;form action="/shorten" method="POST">
        &lt;input type="text" name="url" placeholder="Enter URL" required>
        &lt;button type="submit">Shorten&lt;/button>
    &lt;/form>
    </body> </html>

    templates/result.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Shortened URL&lt;/title>
    </head> <body>
    &lt;h1>Your Shortened URL&lt;/h1>
    &lt;p>&lt;a href="{{ short_url }}">{{ request.url_root }}{{ short_url }}&lt;/a>&lt;/p>
    &lt;a href="/">Shorten another URL&lt;/a>
    </body> </html>

    Step 4: Run the Application

    In your terminal, navigate to your project directory and run:

    python app.py
    

    Step 5: Access the Application

    Open your web browser and go to http://127.0.0.1:5000/. You should see the URL shortener interface. Enter a URL, and it will provide you with a shortened version.

  • Read Files

    Reading from a file involves opening the file, reading its contents, and then closing the file to free up system resources. Python provides several methods to read from a file, each suited for different use cases.

    Opening a File for Reading

    Opening a file is the first step in reading its contents. In Python, you use the open() function to open a file. This function requires at least one argument, the filename, and optionally a mode that specifies the purpose of opening the file.

    To open a file for reading, you use the mode ‘r’. This is the default mode, so you can omit it if you only need to read from the file.

    Reading a File Using read() Method

    The read() method is used to read the contents of a file in Python. It reads the entire content of the file as a single string. This method is particularly useful when you need to process the whole file at once.

    Syntax

    Following is the basic syntax of the read() method in Python −

    file_object.read(size)

    Where,

    • file_object is the file object returned by the open() function.
    • size is the number of bytes to read from the file. This parameter is optional. If omitted or set to a negative value, the method reads until the end of the file.

    Example

    In the following example, we are opening the file “example.txt” in read mode. We then use the read() method to read the entire content of the file −

    # Open the file in read modefile=open('example.txt','r')# Read the entire content of the file
    content =file.read()# Print the contentprint(content)# Close the filefile.close()

    After executing the above code, we get the following output −

    welcome to Tutorialspoint.
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Reading a File Using readline() Method

    The readline() method is used to read one line from a file at a time. This method is useful when you need to process a file line by line, especially for large files where reading the entire content at once is not practical.

    Syntax

    Following is the basic syntax of the readline() method in Python −

    file_object.readline(size)

    Where,

    • file_object is the file object returned by the open() function.
    • size is an optional parameter specifying the maximum number of bytes to read from the line. If omitted or set to a negative value, the method reads until the end of the line.

    Example

    In the example below, we are opening the file “example.txt” in read mode. We then use the readline() method to read the first line of the file −

    # Open the file in read modefile=open('example.txt','r')# Read the first line of the file
    line =file.readline()# Print the lineprint(line)# Close the filefile.close()

    Following is the output of the above code −

    welcome to Tutorialspoint.
    

    Reading a File Using readlines() Method

    The readlines() method reads all the lines from a file and returns them as a list of strings. Each string in the list represents a single line from the file, including the newline character at the end of each line.

    This method is particularly useful when you need to process or analyse all lines of a file at once.

    Syntax

    Following is the basic syntax of the readlines() method in Python −

    file_object.readlines(hint)

    Where,

    • file_object is the file object returned by the open() function.
    • hint is an optional parameter that specifies the number of bytes to read. If specified, it reads lines up to the specified bytes, not necessarily reading the entire file.

    Example

    In this example, we are opening the file “example.txt” in read mode. We then use the readlines() method to read all the lines from the file and return them as a list of strings −

    # Open the file in read modefile=open('example.txt','r')# Read all lines from the file
    lines =file.readlines()# Print the linesfor line in lines:print(line, end='')# Close the filefile.close()

    Output of the above code is as shown below −

    welcome to Tutorialspoint.
    Hi Surya.
    How are you?.
    

    Using “with” Statement

    The “with” statement in Python is used for exception handling. When dealing with files, using the “with” statement ensures that the file is properly closed after reading, even if an exception occurs.

    When you use a with statement to open a file, the file is automatically closed at the end of the block, even if an error occurs within the block.

    Example

    Following is a simple example of using the with statement to open, read, and print the contents of a file −

    # Using the with statement to open a filewithopen('example.txt','r')asfile:
       content =file.read()print(content)

    We get the output as follows −

    welcome to Tutorialspoint.
    Hi Surya.
    How are you?.
    

    Reading a File in Binary Mode

    By default, read/write operation on a file object are performed on text string data. If we want to handle files of different types, such as media files (mp3), executables (exe), or pictures (jpg), we must open the file in binary mode by adding the ‘b’ prefix to the read/write mode.

    Writing to a Binary File

    Assuming that the test.bin file has already been written in binary mode −

    # Open the file in binary write modewithopen('test.bin','wb')as f:
       data =b"Hello World"
       f.write(data)

    Example

    To read a binary file, we need to open it in ‘rb’ mode. The returned value of the read() method is then decoded before printing −

    # Open the file in binary read modewithopen('test.bin','rb')as f:
       data = f.read()print(data.decode(encoding='utf-8'))

    It will produce the following output −

    Hello World
    

    Reading Integer Data From a File

    To write integer data to a binary file, the integer object should be converted to bytes using the to_bytes() method.

    Writing an Integer to a Binary File

    Following is an example on how to write an integer to a binary file −

    # Convert the integer to bytes and write to a binary file
    n =25
    data = n.to_bytes(8,'big')withopen('test.bin','wb')as f:
       f.write(data)

    Reading an Integer from a Binary File

    To read back the integer data from the binary file, convert the output of the read() function back to an integer using the from_bytes() method −

    # Read the binary data from the file and convert it back to an integerwithopen('test.bin','rb')as f:
       data = f.read()
       n =int.from_bytes(data,'big')print(n)

    Reading Float Data From a File

    For handling floating-point data in binary files, we need to use the struct module from Python’s standard library. This module helps convert between Python values and C structs represented as Python bytes objects.

    Writing a Float to a Binary File

    To write floating-point data to a binary file, we use the struct.pack() method to convert the float into a bytes object −

    import struct
    
    # Define a floating-point number
    x =23.50# Pack the float into a binary format
    data = struct.pack('f', x)# Open the file in binary write mode and write the packed datawithopen('test.bin','wb')as f:
       f.write(data)

    Reading Float Numbers from a Binary File

    To read floating-point data from a binary file, we use the struct.unpack() method to convert the bytes object back into a float −

    import struct
    
    # Open the file in binary read modewithopen('test.bin','rb')as f:# Read the binary data from the file
       data = f.read()# Unpack the binary data to retrieve the float
       x = struct.unpack('f', data)[0]# Print the float valueprint(x)

    Reading and Writing to a File Using “r+” Mode

    When a file is opened for reading (with ‘r’ or ‘rb’), writing data is not possible unless the file is closed and reopened in a different mode. To perform both read and write operations simultaneously, we add the ‘+’ character to the mode parameter. Using ‘w+’ or ‘r+’ mode enables using both write() and read() methods without closing the file.

    The File object also supports the seek() function, which allows repositioning the read/write pointer to any desired byte position within the file.

    Syntax

    Following is the syntax for seek() method −

    fileObject.seek(offset[, whence])

    Parameters

    • offset − This is the position of the read/write pointer within the file.
    • whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.

    Example

    The following program opens a file in ‘r+’ mode (read-write mode), seeks a certain position in the file, and reads data from that position −

    # Open the file in read-write modewithopen("foo.txt","r+")as fo:# Move the read/write pointer to the 10th byte position
       fo.seek(10,0)# Read 3 bytes from the current position
       data = fo.read(3)# Print the read dataprint(data)

    After executing the above code, we get the following output −

    rat
    

    Reading and Writing to a File Simultaneously in Python

    When a file is opened for writing (with ‘w’ or ‘a’), it is not possible to read from it, and attempting to do so will throw an UnsupportedOperation error.

    Similarly, when a file is opened for reading (with ‘r’ or ‘rb’), writing to it is not allowed. To switch between reading and writing, you would typically need to close the file and reopen it in the desired mode.

    To perform both read and write operations simultaneously, you can add the ‘+’ character to the mode parameter. Using ‘w+’ or ‘r+’ mode enables both write() and read() methods without needing to close the file.

    Additionally, the File object supports the seek() function, which allows you to reposition the read/write pointer to any desired byte position within the file.

    Example

    In this example, we open the file in ‘r+’ mode and write data to the file. The seek(0) method repositions the pointer to the beginning of the file −

    # Open the file in read-write modewithopen("foo.txt","r+")as fo:# Write data to the file
       fo.write("This is a rat race")# Rewind the pointer to the beginning of the file
       fo.seek(0)# Read data from the file
       data = fo.read()print(data)

    Reading a File from Specific Offset

    We can set the he file’s current position at the specified offset using the seek() method.

    • If the file is opened for appending using either ‘a’ or ‘a+’, any seek() operations will be undone at the next write.
    • If the file is opened only for writing in append mode using ‘a’, this method is essentially a no-op, but it remains useful for files opened in append mode with reading enabled (mode ‘a+’).
    • If the file is opened in text mode using ‘t’, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior.

    Note that not all file objects are seekable.

    Example

    The following example demonstrates how to use the seek() method to perform simultaneous read/write operations on a file. The file is opened in w+ mode (read-write mode), some data is added, and then the file is read and modified at a specific position −

    Open Compiler

    # Open a file in read-write mode
    fo =open("foo.txt","w+")# Write initial data to the file
    fo.write("This is a rat race")# Seek to a specific position in the file
    fo.seek(10,0)# Read a few bytes from the current position
    data = fo.read(3)print("Data read from position 10:", data)# Seek back to the same position
    fo.seek(10,0)# Overwrite the earlier contents with new text
    fo.write("cat")# Rewind to the beginning of the file
    fo.seek(0,0)# Read the entire file content
    data = fo.read()print("Updated file content:", data)# Close the file
    fo.close()

    Following is the output of the above code −

    Data read from position 10: rat
    Updated file content: This is a cat race
  • Photo Gallery Website

    Project Structure

    photo-gallery/
    ├── index.html
    ├── styles.css
    └── script.js
    

    1. index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;link rel="stylesheet" href="styles.css">
    &lt;title>Photo Gallery&lt;/title>
    </head> <body>
    &lt;div class="gallery">
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 1">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 2">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 3">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 4">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 5">
        &lt;/div>
        &lt;div class="gallery-item">
            &lt;img src="https://via.placeholder.com/300" alt="Photo 6">
        &lt;/div>
    &lt;/div>
    &lt;div class="modal" id="modal">
        &lt;span class="close" id="close">&amp;times;&lt;/span>
        &lt;img class="modal-content" id="modal-img">
    &lt;/div>
    &lt;script src="script.js">&lt;/script>
    </body> </html>

    2. styles.css

    cssCopy codebody {
    
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    } .gallery {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    padding: 20px;
    } .gallery-item {
    flex: 1 1 calc(33.333% - 10px);
    cursor: pointer;
    } .gallery-item img {
    width: 100%;
    border-radius: 8px;
    transition: transform 0.3s;
    } .gallery-item img:hover {
    transform: scale(1.05);
    } .modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto;
    background-color: rgba(0, 0, 0, 0.8);
    } .modal-content {
    margin: auto;
    display: block;
    max-width: 80%;
    } .close {
    position: absolute;
    top: 20px;
    right: 30px;
    color: white;
    font-size: 40px;
    font-weight: bold;
    cursor: pointer;
    }

    3. script.js

    javascriptCopy codeconst galleryItems = document.querySelectorAll('.gallery-item img');
    const modal = document.getElementById('modal');
    const modalImg = document.getElementById('modal-img');
    const closeModal = document.getElementById('close');
    
    galleryItems.forEach(item => {
    
    item.addEventListener('click', () =&gt; {
        modal.style.display = 'block';
        modalImg.src = item.src;
    });
    }); closeModal.addEventListener('click', () => {
    modal.style.display = 'none';
    }); window.addEventListener('click', (event) => {
    if (event.target === modal) {
        modal.style.display = 'none';
    }
    });

    Instructions

    1. Create the Project Structure: Make a new directory and create the three files listed above.
    2. Copy the Code: Copy the respective code into each file.
    3. Open index.html: Open this file in a web browser to view your photo gallery.
  • Write to File

    Writing to a file involves opening the file in a specific mode, writing data to it, and then closing the file to ensure that all data is saved and resources are released. Python provides a built-in function open() to handle file operations and various methods for writing data.

    Opening a File for Writing

    Opening a file for writing is the first step in performing write operations in Python. The open() function is used to open files in different modes, each suited for specific use cases.

    The open() Function

    The open() function in Python is used to open a file. It requires at least one argument, the name of the file, and can take an optional second argument that specifies the mode in which the file should be opened.

    File Modes for Writing

    Following are the main modes you can use to open a file for writing −

    • w (Write mode) − Opens the file for writing. If the file exists, it truncates (empties) the file before writing. If the file does not exist, it creates a new file.
    • a (Append Mode) − Data is written at the end of the file. If the file does not exist, it creates a new file.
    • x (Exclusive Creation Mode) − Opens the file for exclusive creation. If the file already exists, the operation fails.
    • b (Binary Mode) − When used with other modes, opens the file in binary mode.
    • + (Update Mode) − Opens the file for updating (reading and writing).

    Example: Opening a File in Write Mode

    This mode is used when you want to write data to a file, starting from scratch each time the file is opened −

    Open Compiler

    file=open("example.txt","w")file.write("Hello, World!")file.close()print("File opened successfully!!")

    Following is the output obtained −

    File opened successfully!!
    

    Example: Opening a File in Append Mode

    This mode is used when you want to add data to the end of the file without altering its existing contents −

    Open Compiler

    file=open("example.txt","a")file.write("Appending this line.\n")file.close()print("File opened successfully!!")

    This will produce the following result −

    File opened successfully!!
    

    Writing to a File Using write() Method

    The write() method is used to write a single string to a file. This makes it suitable for various text-based file operations.

    The write() method takes a single argument: the string that you want to write to the file. It writes the exact content of the string to the file without adding any additional characters, such as newlines.

    Example

    In the following example, we are opening the file “example.txt” in write mode. We then use the write() method to write a string to the file −

    Open Compiler

    # Open a file in write modewithopen("example.txt","w")asfile:file.write("Hello, World!\n")file.write("This is a new line.\n")print("File opened successfully!!")

    Following is the output of the above code −

    File opened successfully!!
    

    Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

    Writing to a File Using writelines() Method

    The writelines() method is used to write a list of strings to a file. Each string in the list is written to the file sequentially without adding any newline characters automatically.

    Example

    In this example, we are creating a list of strings, lines, with each string ending in a newline character. We then open a file “example.txt” in write mode and use the writelines() method to write all the strings in the list to the file in one operation −

    Open Compiler

    # List of lines to write to the file
    lines =["First line\n","Second line\n","Third line\n"]# Open a file in write modewithopen("example.txt","w")asfile:file.writelines(lines)print("File opened successfully!!")

    The output obtained is as shown below −

    File opened successfully!!
    

    Writing to a New File

    Writing to a new file in Python involves creating a new file (or overwriting an existing one) and writing the desired content to it. Here, we will explain the steps involved in writing to a new file −

    • Open the File − Use the open() function to create or open a file in write mode (“w” or “wb” for binary files).
    • Write Data − Use the write() or writelines() method to write data to the file.
    • Close the File − Ensure the file is properly closed after writing, generally using the “with” statement for automatic handling.

    Example

    In the example below, we create a “foo.txt” file and write given content in that file and finally close that file −

    # Open a file
    fo =open("foo.txt","w")
    fo.write("Python is a great language.\nYeah its great!!\n")# Close opened file
    fo.close()

    If you open this file with any text editor application such as Notepad, it will have the following content −

    Python is a great language.
    Yeah its great!!
    

    Writing to a New File in Binary Mode

    By default, read/write operations on a file object are performed on text string data. If we need to handle files of different types, such as media files (mp3), executables (exe), or pictures (jpg), we must open the file in binary mode by adding the ‘b’ prefix to the read/write mode.

    Writing Binary Data to a File

    To write binary data to a file, open the file in binary write mode (‘wb’). The following example demonstrates this −

    # Open a file in binary write modewithopen('test.bin','wb')as f:# Binary data
       data =b"Hello World"  
       f.write(data)

    Converting Text Strings to Bytes

    Conversion of a text string to bytes can be done using the encode() function. This is useful when you need to write text data as binary data −

    # Open a file in binary write modewithopen('test.bin','wb')as f:# Convert text string to bytes
       data ="Hello World".encode('utf-8')  
       f.write(data)

    Writing to an Existing File

    When an existing file is opened in write mode (‘w’), its previous contents are erased. Opening a file with write permission treats it as a new file. To add data to an existing file without erasing its contents, you should open the file in append mode (‘a’).

    Example

    The following example demonstrates how to open a file in append mode and add new text to it −

    # Open a file in append mode
    fo =open("foo.txt","a")
    text ="TutorialsPoint has a fabulous Python tutorial"
    fo.write(text)# Close opened file
    fo.close()

    If you open this file with any text editor application such as Notepad, it will have the following content −

    Python is a great language.
    Yeah its great!!
    TutorialsPoint has a fabulous Python tutorial
    

    Writing to a File in Reading and Writing Modes

    When a file is opened for writing using ‘w’ or ‘a’, it is not possible to perform write operations at any earlier byte position in the file. The ‘w+’ mode, however, allows both reading and writing operations without closing the file. The seek() function is used to move the read/write pointer to any desired byte position within the file.

    Using the seek() Method

    The seek() method is used to set the position of the read/write pointer within the file. The syntax for the seek() method is as follows −

    fileObject.seek(offset[, whence])

    Where,

    • offset − This is the position of the read/write pointer within the file.
    • whence − This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek relative to the current position and 2 means seek relative to the file’s end.

    Example

    The following program demonstrates how to open a file in read-write mode (‘w+’), write some data, seek a specific position, and then overwrite part of the file’s content −

    # Open a file in read-write mode
    fo =open("foo.txt","w+")# Write initial data to the file
    fo.write("This is a rat race")# Move the read/write pointer to the 10th byte
    fo.seek(10,0)# Read 3 bytes from the current position
    data = fo.read(3)# Move the read/write pointer back to the 10th byte
    fo.seek(10,0)# Overwrite the existing content with new text
    fo.write('cat')# Close the file
    fo.close()

    If we open the file in read mode (or seek to the starting position while in ‘w+’ mode) and read the contents, it will show the following −

    This is a cat race
  • Feedback and Survey Tool

    Step 1: Setup the Project

    1. Initialize a new Node.js project:
    mkdir feedback-survey-tool cd feedback-survey-tool npm init -y npm install express body-parser cors
    1. Create the project structure:
    feedback-survey-tool/ ├── server.js ├── public/ │ └── index.html └── package.json

    Step 2: Create the Backend (server.js)

    // server.js
    const express = require('express');
    const bodyParser = require('body-parser');
    const cors = require('cors');
    
    const app = express();
    const PORT = process.env.PORT || 3000;
    
    let feedbacks = []; // In-memory storage for feedbacks
    
    app.use(cors());
    app.use(bodyParser.json());
    app.use(express.static('public'));
    
    // Endpoint to submit feedback
    app.post('/api/feedback', (req, res) => {
    
    const feedback = req.body;
    feedbacks.push(feedback);
    res.status(201).json({ message: 'Feedback submitted successfully!' });
    }); // Endpoint to retrieve feedbacks app.get('/api/feedback', (req, res) => {
    res.json(feedbacks);
    }); // Start the server app.listen(PORT, () => {
    console.log(Server is running on http://localhost:${PORT});
    });

    Step 3: Create the Frontend (index.html)

    <!-- public/index.html -->
    <!DOCTYPE html>
    <html lang="en">
    <head>
    
    &lt;meta charset="UTF-8">
    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0">
    &lt;title>Feedback and Survey Tool&lt;/title>
    &lt;style>
        body { font-family: Arial, sans-serif; }
        form { margin-bottom: 20px; }
        .feedback-list { margin-top: 20px; }
    &lt;/style>
    </head> <body>
    &lt;h1>Feedback and Survey Tool&lt;/h1>
    &lt;form id="feedbackForm">
        &lt;label for="name">Name:&lt;/label>
        &lt;input type="text" id="name" required>
        &lt;br>
        &lt;label for="message">Feedback:&lt;/label>
        &lt;textarea id="message" required>&lt;/textarea>
        &lt;br>
        &lt;button type="submit">Submit Feedback&lt;/button>
    &lt;/form>
    &lt;div class="feedback-list" id="feedbackList">&lt;/div>
    &lt;script>
        const form = document.getElementById('feedbackForm');
        const feedbackList = document.getElementById('feedbackList');
        // Function to submit feedback
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const name = document.getElementById('name').value;
            const message = document.getElementById('message').value;
            const response = await fetch('/api/feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ name, message })
            });
            if (response.ok) {
                alert('Feedback submitted!');
                form.reset();
                loadFeedbacks();
            }
        });
        // Function to load feedbacks
        async function loadFeedbacks() {
            const response = await fetch('/api/feedback');
            const feedbacks = await response.json();
            feedbackList.innerHTML = feedbacks.map(feedback => 
                &amp;lt;div&gt;&amp;lt;strong&gt;${feedback.name}:&amp;lt;/strong&gt; ${feedback.message}&amp;lt;/div&gt;
            ).join('');
        }
        // Load feedbacks on page load
        loadFeedbacks();
    &lt;/script>
    </body> </html>

    Step 4: Run the Application

    1. Start the server:
    node server.js
    1. Open your browser and go to:
    http://localhost:3000