Skip to content
chatmodel

Code Assistant

Small bits of code, written and explained

A script to rename your holiday photos, a spreadsheet formula that won't work, a snippet from a forum you don't understand. Describe what you need or paste the code, pick the task, and Code Assistant does the rest.

Open Code Assistant

Free to start · works in your browser

How it works

  1. 1 In the Input box, describe what you need or paste your code.
  2. 2 Pick a Task (for example Write Code or Debug) and a Language (for example Python).
  3. 3 Press Run and read the code and the notes in the Output tab.

Real examples

See what it does

What you put in, and what Code Assistant gave back. Made with the same instructions and model the tool uses in chatmodel, one try each.

What you put in

I have a folder on my laptop called "Italy 2025" with about 400 photos from my phone. They all have names like IMG_4821.JPG. I'd like a small Python script that renames every photo in the folder using the date it was taken, like 2025-06-14_001.jpg, 2025-06-14_002.jpg, and so on, so they sort in order. Please don't delete anything, and tell me how to run it on a Mac. I've never run a script before.

  • Task: write code
  • Language: python

What you get back

Photo Renaming Script

This script renames JPEG images in a specified directory based on their EXIF creation date, ensuring chronological sorting.

Features

  • EXIF Date Extraction: Reads the EXIF data of JPEG files to determine the original capture date and time.
  • Chronological Renaming: Renames files in the format YYYY-MM-DD_NNN.jpg, where NNN is a sequential counter for each day.
  • Error Handling: Gracefully handles files without EXIF data or files that are not JPEGs.
  • Safety First: Does not delete original files; renames them in place.

Prerequisites

  • Python 3: Ensure you have Python 3 installed on your Mac. You can check this by opening the Terminal and typing python3 --version. If not installed, download it from python.org.
  • Pillow Library: This script uses the Pillow library to read EXIF data. Install it using pip:
    pip3 install Pillow
    

Python Script

import os
import sys
from datetime import datetime
from PIL import Image
from PIL.ExifTags import TAGS

def get_creation_date(filepath):
    """
    Retrieves the creation date from a JPEG file's EXIF data.

    Args:
        filepath (str): The full path to the image file.

    Returns:
        datetime or None: A datetime object representing the creation date,
                          or None if EXIF data is not found or unreadable.
    """
    try:
        image = Image.open(filepath)
        exif_data = image._getexif()

        if exif_data is None:
            return None

        # Common EXIF tags for date/time original
        # 36867 is DateTimeOriginal
        # 306 is DateTime
        date_tag = None
        for tag_id, value in exif_data.items():
            tag_name = TAGS.get(tag_id, tag_id)
            if tag_name in ('DateTimeOriginal', 'DateTime'):
                date_tag = value
                break

        if date_tag:
            # EXIF date format is usually 'YYYY:MM:DD HH:MM:SS'
            return datetime.strptime(date_tag, '%Y:%m:%d %H:%M:%S')
    except IOError:
        print(f"Warning: Could not open or read EXIF data for {filepath}. Skipping.")
        return None
    except Exception as e:
        print(f"Warning: An unexpected error occurred while processing EXIF for {filepath}: {e}. Skipping.")
        return None
    return None

def rename_photos_in_directory(directory_path):
    """
    Renames all JPEG photos in a given directory based on their creation date.

    Args:
        directory_path (str): The path to the directory containing the photos.
    """
    if not os.path.isdir(directory_path):
        print(f"Error: Directory '{directory_path}' not found.")
        return

    files = [f for f in os.listdir(directory_path) if os.path.isfile(os.path.join(directory_path, f))]
    # Filter for JPEG files and ensure case-insensitivity for extensions
    jpeg_files = sorted([f for f in files if f.lower().endswith(('.jpg', '.jpeg'))])

    if not jpeg_files:
        print(f"No JPEG files found in '{directory_path}'.")
        return

    date_counts = {}  # To keep track of sequence numbers per day
    renamed_count = 0

    print(f"Processing photos in: {directory_path}")

    for filename in jpeg_files:
        original_filepath = os.path.join(directory_path, filename)
        creation_date = get_creation_date(original_filepath)

        if creation_date:
            date_str = creation_date.strftime('%Y-%m-%d')
            
            # Increment counter for this date
            if date_str not in date_counts:
                date_counts[date_str] = 0
            date_counts[date_str] += 1
            sequence_num = date_counts[date_str]

            # Format the new filename: YYYY-MM-DD_NNN.jpg
            new_filename = f"{date_str}_{sequence_num:03d}.jpg"
            new_filepath = os.path.join(directory_path, new_filename)

            # Avoid renaming if the file is already named correctly or if the new name conflicts
            if filename == new_filename:
                print(f"Skipping already correctly named file: {filename}")
                continue
            if os.path.exists(new_filepath):
                print(f"Warning: Target file '{new_filename}' already exists. Skipping rename for '{filename}'.")
                continue

            try:
                os.rename(original_filepath, new_filepath)
                print(f"Renamed '{filename}' to '{new_filename}'")
                renamed_count += 1
            except OSError as e:
                print(f"Error renaming '{filename}' to '{new_filename}': {e}")
        else:
            print(f"Skipping '{filename}': Could not determine creation date from EXIF.")

    print(f"\nFinished processing. {renamed_count} photos renamed.")

if __name__ == "__main__":
    # IMPORTANT: Replace this with the actual path to your "Italy 2025" folder.
    # For example: "/Users/yourusername/Pictures/Italy 2025"
    # You can drag and drop the folder onto the Terminal window to get its path.
    
    # Example using command-line argument:
    if len(sys.argv) > 1:
        folder_to_process = sys.argv[1]
    else:
        # If no argument is provided, prompt the user or use a default (use with caution)
        # folder_to_process = input("Enter the full path to the photo folder: ")
        # For safety, if no argument is given, it's better to exit and ask for it.
        print("Usage: python rename_photos.py <path_to_your_photo_folder>")
        print("Example: python rename_photos.py /Users/yourusername/Pictures/Italy 2025")
        sys.exit(1)

    rename_photos_in_directory(folder_to_process)

How to Run the Script on a Mac

  1. Save the Script:

    • Open a plain text editor (like TextEdit, VS Code, Sublime Text, etc.).
    • Copy the Python code above and paste it into the editor.
    • Save the file with a .py extension, for example, rename_photos.py. Save it in a place you can easily find, like your Documents folder.
  2. Open Terminal:

    • Go to your Applications folder, then Utilities, and open Terminal.
  3. Navigate to the Script's Directory:

    • In the Terminal, type cd (note the space after cd).
    • Drag and drop the folder where you saved rename_photos.py onto the Terminal window. This will automatically fill in the path.
    • Press Enter.
    • Example: cd /Users/yourusername/Documents
  4. Run the Script:

    • To run the script, you need to provide the path to your "Italy 2025" folder as an argument.

    • Type the following command, replacing /path/to/your/Italy 2025 with the actual path to your folder:

      python3 rename_photos.py /path/to/your/Italy 2025
      
    • Tip: You can get the path to your "Italy 2025" folder by opening Finder, navigating to the folder, and then dragging and dropping the "Italy 2025" folder itself onto the Terminal window after you've typed python3 rename_photos.py (with the space).

    • Example: If your photos are in your Pictures folder, your command might look like this:

      python3 rename_photos.py /Users/yourusername/Pictures/Italy\ 2025
      

      (Note the backslash \ before the space in "Italy 2025" if you're typing the path manually. Dragging and dropping usually handles this automatically.)

  5. Review the Output:

    • The script will print messages indicating which files are being renamed or if any issues are encountered.
    • Once it finishes, check your "Italy 2025" folder to confirm the renaming.

Important Notes

  • Backup First: Although the script is designed not to delete files, it's always a good practice to back up your photos before running any renaming script.
  • EXIF Data: The script relies on the EXIF data embedded in your photos. If your photos have had their EXIF data stripped or modified, the script might not be able to determine the original date. In such cases, those files will be skipped and a warning will be printed.
  • Case Sensitivity: The script handles file extensions in a case-insensitive manner (.JPG, .jpg, .jpeg, .JPEG).
  • File Conflicts: If a file with the target name already exists (e.g., after a previous run or if you have manually created files), the script will skip renaming the current file to avoid overwriting.
  • Permissions: Ensure your user account has permission to rename files in the target directory.

Done in about 7 seconds

Try it with your own text

What people use it for

What Code Assistant does

Code Assistant is like having an experienced programmer next to you. You describe what you need, or paste some code, and it gives you clean code with short notes on the tricky parts.

Code always comes in a separate box, so it’s easy to copy. It’s written to be tidy and modern, to check for things that could go wrong, and never to include passwords or private keys.

You don’t need to be a programmer. Most people use it for small, practical jobs: a formula, a script to sort files, a change to a web page.

What you can change

Task

  • Write Code: new code from your description.
  • Explain Code: what a piece of code does, step by step.
  • Debug: finds the mistake, fixes it and explains why it went wrong.
  • Optimize: makes code faster or easier to read, and says what it traded off.
  • Convert: rewrites code in another language, the way that language is usually written.
  • Code Review: points out risky or messy parts and suggests improvements.

Language: JavaScript, TypeScript, Python, Java, C#, C++, Go, Rust, PHP, Ruby, Swift or Kotlin.

What it won’t do

  • It won’t run the code for you or touch your files. You copy it and run it yourself.
  • It can’t see your computer, so it guesses details you don’t give it, like folder names.
  • It can make mistakes. Test on a copy first, and don’t run code you don’t understand on important files.

Just want to understand a topic, not code it? Try Learn. Building a budget? The household budget guide or Create a Spreadsheet may be quicker. See all the tools.

Open Code Assistant

Frequently asked questions

Do I need to know how to code?

No. You can describe what you want in plain words. Say you're a beginner and ask it to explain how to use the result.

What tasks can I pick?

Write Code, Explain Code, Debug, Optimize, Convert and Code Review.

Which languages does it support?

The Language menu has JavaScript, TypeScript, Python, Java, C#, C++, Go, Rust, PHP, Ruby, Swift and Kotlin.

Can it help with Excel or Google Sheets formulas?

Yes. Paste the formula, describe your columns and pick Debug. Spreadsheet formulas aren't in the Language menu, so just describe which app you use.

Is the code safe to run?

It's written to check its inputs and avoid risky shortcuts, but always read the notes and test on a copy of your files first.

All of these models, in one place

Chat, images, video and tools with the best AI models. Switch between them whenever you want.

Start for free

Chatmodel is an independent service offering access to third-party AI models. AI can make mistakes. Using Chatmodel means you agree to our Terms and Privacy Policy.