A Python Script to Extract Image Titles And Save As CSV

A Python Script to Extract Image Titles And Save As CSV

Introduction

Creating executable files from Python scripts is a common requirement for developers who want to distribute their programs without requiring users to have Python installed. In this article, we’ll go through the steps to write a Python script that extracts the titles of images in a directory and saves them to a CSV file. We’ll then convert this script into an executable file that runs on Windows operating system.

Prerequisites

Before we begin, make sure you have the following installed on your system:

  1. Python: Download and install Python from the official website. Ensure that Python is added to your system’s PATH during installation.

  2. Visual Studio Code: Download and install Visual Studio Code.

  3. Pip: Pip should come with Python, but you can verify it by running pip --version in the command prompt.

Step 1: Writing the Python Script

First, let's create a Python script that will extract the titles (filenames without extensions) of images in a specified folder and save these titles to a CSV file.

1. Create a New Python File in VS Code

  1. Open Visual Studio Code.

  2. Open a new terminal within VS Code by going to View -> Terminal or pressing Ctrl + ` .

  3. Navigate to the folder where you want to create your script using the cd command.

     cd path\to\your\folder
    
  4. Create a new Python file by going to File -> New File and saving it with the name extract_image_titles.py.

2. Write the Python Code

Copy and paste the following Python code into your extract_image_titles.py file:

import os
import csv

def extract_image_titles(image_folder, csv_filename):
    # List to hold image titles
    image_titles = []

    # Iterate through all files in the folder
    for filename in os.listdir(image_folder):
        # Check if the file is an image (you can add more extensions as needed)
        if filename.endswith(('.png', '.jpg', '.jpeg', '.gif', '.bmp')):
            # Extract the title (filename without extension)
            title = os.path.splitext(filename)[0]
            image_titles.append(title)

    # Write the titles to a CSV file
    with open(csv_filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Image Title'])  # Header
        for title in image_titles:
            writer.writerow([title])

if __name__ == "__main__":
    # Define the folder containing the images and the output CSV filename
    image_folder = 'path\\to\\your\\image\\folder'  # Replace with the path to your images folder
    csv_filename = 'image_titles.csv'

    # Extract image titles and write to CSV
    extract_image_titles(image_folder, csv_filename)
    print(f"Titles of images have been saved to {csv_filename}")

Step 2: Running the Python Script

1. Modify the Script

Replace path\\to\\your\\image\\folder with the actual path to the folder containing your images.

For example:

image_folder = 'C:\\Users\\YourUsername\\Pictures\\Images'

2. Run the Script

To test the script, follow these steps:

  1. Save the script in VS Code.

  2. In the terminal within VS Code, run the script using the following command:

     python extract_image_titles.py
    

If the script runs successfully, it will create a image_titles.csv file in the same directory, containing the titles of all the images in your specified folder.

Step 3: Installing PyInstaller

To convert the Python script into an executable file, we’ll use a tool called PyInstaller.

1. Install PyInstaller

Install PyInstaller via pip by running the following command in the terminal:

pip install pyinstaller

2. Verify the Installation

To verify that PyInstaller has been installed correctly, you can check its version by running:

pyinstaller --version

Step 4: Creating an Executable File

Now that PyInstaller is installed, you can create an executable from your Python script.

1. Generate the Executable

In the terminal, navigate to the directory containing your Python script and run the following command:

pyinstaller --onefile extract_image_titles.py

This command tells PyInstaller to create a single executable file from the extract_image_titles.py script.

2. Understanding the Output

Once the command finishes executing, PyInstaller will generate several folders and files in your working directory:

  • build/: This folder contains temporary files used during the creation of the executable.

  • dist/: This folder contains the final executable file, extract_image_titles.exe.

  • extract_image_titles.spec: This is a spec file that PyInstaller uses to build the executable.

3. Running the Executable

To run the executable:

  1. Navigate to the dist/ folder in File Explorer.

  2. Double-click on extract_image_titles.exe to run the program.

The executable will run the same as the Python script, creating the image_titles.csv file in the same directory where the executable is located.

Troubleshooting

  • Missing DLLs: If the executable doesn’t run on another machine, it might be missing some DLLs. You can bundle these by using the --add-data or --add-binary options with PyInstaller.

  • Antivirus False Positives: Some antivirus programs might flag executables created with PyInstaller as potential threats. This is usually a false positive, but be sure to test the executable thoroughly.

Conclusion

By following the steps outlined in this article, you have successfully created a Python script that extracts the titles of images and saves them to a CSV file. You also learned how to convert this script into an executable file. This executable can now be run on any Windows machine, making it easy to distribute and use without requiring Python to be installed on the target system.

This process not only demonstrates the power and flexibility of Python but also shows how easily Python scripts can be packaged and shared in a user-friendly way.