```python
# Dependencies: pip install Pillow
"""
Image resizer script.
Scans a folder for .jpg and .png images, resizes any image whose longest side
exceeds 1920px down to 1920px while preserving aspect ratio, and saves copies
into a 'resized' subfolder.
"""
import argparse
import sys
from pathlib import Path
from typing import Iterable
from PIL import Image, UnidentifiedImageError
MAX_SIZE: int = 1920
SUPPORTED_EXTENSIONS: tuple[str, ...] = (".jpg", ".jpeg", ".png")
def iter_images(folder: Path) -> Iterable[Path]:
"""Yield image file paths in `folder` with supported extensions."""
for path in folder.iterdir():
if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS:
yield path
def resize_if_needed(image_path: Path, output_dir: Path, max_size: int = MAX_SIZE) -> bool:
"""
Resize the image at `image_path` if its longest side exceeds `max_size`.
Saves the resulting image (resized or original copy) to `output_dir`.
Returns True if the image was actually resized, False otherwise.
"""
try:
with Image.open(image_path) as img:
width, height = img.size
longest = max(width, height)
output_path = output_dir / image_path.name
if longest > max_size:
# Use thumbnail for in-place proportional resize (preserves aspect ratio).
scale = max_size / longest
new_size = (int(width * scale), int(height * scale))
resized = img.resize(new_size, Image.LANCZOS)
# Preserve mode appropriately for JPEG (no alpha channel).
if image_path.suffix.lower() in (".jpg", ".jpeg") and resized.mode in ("RGBA", "P"):
resized = resized.convert("RGB")
resized.save(output_path)
print(f"Resized: {image_path.name} ({width}x{height}) -> {new_size[0]}x{new_size[1]}")
return True
else:
# Still save a copy so 'resized' folder contains all processed images.
img.save(output_path)
print(f"Copied (no resize needed): {image_path.name} ({width}x{height})")
return False
except (UnidentifiedImageError, OSError) as exc:
print(f"Skipping {image_path.name}: {exc}", file=sys.stderr)
return False
def main() -> int:
"""Parse CLI args and process images."""
parser = argparse.ArgumentParser(
description="Resize images larger than 1920px on longest side into a 'resized' subfolder."
)
parser.add_argument("input_folder", type=str, help="Path to folder containing images.")
args = parser.parse_args()
input_dir = Path(args.input_folder)
if not input_dir.is_dir():
print(f"Error: '{input_dir}' is not a valid directory.", file=sys.stderr)
return 1
output_dir = input_dir / "resized"
output_dir.mkdir(exist_ok=True)
total = 0
resized_count = 0
for image_path in iter_images(input_dir):
total += 1
if resize_if_needed(image_path, output_dir):
resized_count += 1
print(f"\nDone. Processed {total} image(s); resized {resized_count}.")
print(f"Output folder: {output_dir}")
return 0
if __name__ == "__main__":
sys.exit(main())
```
**How to run**
- Install the dependency: `pip install Pillow`
- Run the script with your image folder path: `python resize_images.py /path/to/images`
- Resized copies will appear in `/path/to/images/resized/`
- Supported file types: `.jpg`, `.jpeg`, `.png`
Turn Natural Language Prompts into Python Scripts
Tested prompts for generate python script from text prompt compared across 5 leading AI models.
If you typed 'generate python script from text prompt' into Google, you already know what you want: describe a task in plain English and get working Python code back. Whether you need a script to rename files in bulk, parse a CSV, call an API, or automate a repetitive workflow, AI code generation lets you skip the boilerplate and get to a running script faster than searching Stack Overflow.
The real question is not whether AI can generate Python from a prompt. It can. The question is which model handles your specific request most reliably, and how to write a prompt that produces clean, runnable code instead of something that almost works. Vague prompts return vague code. Specific prompts return scripts you can actually use.
This page breaks down exactly how to prompt for Python scripts, compares how leading models handle the same request, and shows you where each one wins or fails. If you need a script right now, the examples below are ready to adapt.
When to use this
Generating Python from a text prompt is the right move when you have a clearly defined task but do not want to spend time on syntax, library lookup, or boilerplate. It works best for self-contained scripts, automation tasks, data processing pipelines, and utility tools where the logic is explainable in one or two sentences.
- Automating file system tasks: renaming, sorting, moving, or deduplicating files based on rules
- Parsing or transforming data: reading CSVs, JSONs, or Excel files and outputting a cleaned or reformatted version
- Calling external APIs and processing the response into a report or file
- Scraping a webpage and extracting structured data into a spreadsheet
- Scheduling or triggering repetitive tasks like sending emails, pinging endpoints, or archiving logs
When this format breaks down
- Your project spans multiple files or modules with complex interdependencies. Single-prompt generation breaks down when the task requires understanding an existing codebase rather than generating from scratch.
- You need production-grade security. AI-generated scripts often skip input validation, hardcode credentials, or use deprecated patterns. Never deploy generated code handling auth or payments without a thorough security review.
- The logic involves highly domain-specific rules, such as actuarial calculations or medical device control, where subtle errors in generated code carry real risk and are difficult to spot without deep domain expertise.
- You cannot describe the task clearly yourself. If you cannot write two sentences explaining what the script should do, the model will fill gaps with assumptions, and the result will not match what you need.
The prompt we tested
You are an expert Python developer. Convert the user's natural language description into a complete, working Python script. Output only a single, runnable Python 3 script inside one fenced ```python code block, followed by a brief 2-4 bullet 'How to run' section below it. Include necessary imports, type hints, docstrings, inline comments for non-obvious logic, basic error handling, and an `if __name__ == "__main__":` entry point. Do not invent external APIs or libraries the user didn't request; use the standard library when possible and list any pip dependencies at the top in a comment. User's request: Write a script that scans a folder of images, resizes any image larger than 1920px on its longest side down to 1920px while preserving aspect ratio, and saves the resized copies into a subfolder called 'resized'. It should accept the input folder as a command line argument and support .jpg and .png files. Return the Python script now.
Model comparison
| Model | Quality | Cost | Latency | Tokens |
|---|---|---|---|---|
| Claude Opus 4.7 | 8 | $0.1054 | 14.0s | 301 / 1345 |
| Claude Haiku 4.5 | 8 | $0.0066 | 7.3s | 228 / 1284 |
| GPT-5.4 | 8 | $0.0159 | 13.5s | 210 / 1026 |
| Grok 4.1 Fast Reasoning | 7 | $0.0004 | 13.8s | 360 / 700 |
Outputs
```python
"""
Image resizer script: Resizes images larger than 1920px on the longest side.
Preserves aspect ratio and saves resized copies to a 'resized' subfolder.
pip dependencies: Pillow
"""
import sys
import os
from pathlib import Path
from PIL import Image
import argparse
from typing import Optional
def resize_image(image_path: Path, output_path: Path, max_dimension: int = 1920) -> bool:
"""
Resize an image if its longest side exceeds max_dimension.
Args:
image_path: Path to the source image
output_path: Path where the resized image will be saved
max_dimension: Maximum allowed dimension for the longest side (default 1920)
Returns:
True if image was resized and saved, False if it was already small enough
"""
try:
with Image.open(image_path) as img:
# Get original dimensions
width, height = img.size
longest_side = max(width, height)
# Check if resizing is needed
if longest_side <= max_dimension:
print(f" Skipped (already {width}x{height}): {image_path.name}")
return False
# Calculate new dimensions preserving aspect ratio
scale_factor = max_dimension / longest_side
new_width = int(width * scale_factor)
new_height = int(height * scale_factor)
# Resize using high-quality resampling
resized_img = img.resize((new_width, new_height), Image.Resampling.LANCZOS)
# Save resized image
resized_img.save(output_path, quality=95, optimize=True)
print(f" Resized {width}x{height} → {new_width}x{new_height}: {image_path.name}")
return True
except Exception as e:
print(f" Error processing {image_path.name}: {e}")
return False
def process_images(input_folder: Path, max_dimension: int = 1920) -> None:
"""
Scan a folder for images and resize those exceeding max_dimension.
Args:
input_folder: Path to the folder containing images
max_dimension: Maximum allowed dimension for the longest side (default 1920)
"""
# Validate input folder
if not input_folder.is_dir():
print(f"Error: '{input_folder}' is not a valid directory.")
sys.exit(1)
# Create resized subfolder
resized_folder = input_folder / "resized"
try:
resized_folder.mkdir(exist_ok=True)
except Exception as e:
print(f"Error creating resized folder: {e}")
sys.exit(1)
# Supported image extensions
supported_extensions = {'.jpg', '.jpeg', '.png'}
# Find all image files
image_files = [
f for f in input_folder.iterdir()
if f.is_file() and f.suffix.lower() in supported_extensions
]
if not image_files:
print(f"No .jpg or .png images found in '{input_folder}'.")
return
print(f"Found {len(image_files)} image(s) in '{input_folder}'.")
print(f"Processing images (max dimension: {max_dimension}px)...\n")
resized_count = 0
for image_file in image_files:
output_path = resized_folder / image_file.name
if resize_image(image_file, output_path, max_dimension):
resized_count += 1
print(f"\nProcessing complete! {resized_count} image(s) were resized.")
print(f"Resized images saved to: {resized_folder}")
def main() -> None:
"""Main entry point for the script."""
parser = argparse.ArgumentParser(
description="Resize images larger than 1920px on the longest side while preserving aspect ratio."
)
parser.add_argument(
"input_folder",
type=str,
help="Path to the folder containing images to resize"
)
parser.add_argument(
"--max-dimension",
type=int,
default=1920,
help="Maximum dimension in pixels for the longest side (default: 1920)"
)
args = parser.parse_args()
input_folder = Path(args.input_folder)
process_images(input_folder, args.max_dimension)
if __name__ == "__main__":
main()
```
**How to run:**
- Install Pillow: `pip install Pillow`
- Run with default 1920px limit: `python script.py /path/to/image/folder`
- Run with custom max dimension: `python script.py /path/to/image/folder --max-dimension 1280`
- Resized images will be saved in a `resized` subfolder within the input directory
```python
#!/usr/bin/env python3
"""
Pip dependencies:
- Pillow
Scan a folder for .jpg/.jpeg and .png images, resize any image whose longest
side exceeds 1920 pixels, and save the processed copies into a 'resized'
subfolder within the input folder.
Images smaller than or equal to 1920px on their longest side are copied as-is
into the output folder to ensure all supported images are present there.
"""
from __future__ import annotations
import argparse
import shutil
import sys
from pathlib import Path
from typing import Iterable
from PIL import Image
MAX_LONGEST_SIDE = 1920
SUPPORTED_EXTENSIONS = {".jpg", ".jpeg", ".png"}
def parse_args() -> argparse.Namespace:
"""Parse command-line arguments."""
parser = argparse.ArgumentParser(
description=(
"Resize images larger than 1920px on their longest side and save "
"them into a 'resized' subfolder."
)
)
parser.add_argument(
"input_folder",
type=Path,
help="Path to the folder containing .jpg/.jpeg and .png images.",
)
return parser.parse_args()
def iter_image_files(folder: Path) -> Iterable[Path]:
"""Yield supported image files in the given folder (non-recursive)."""
for path in folder.iterdir():
if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS:
yield path
def calculate_new_size(width: int, height: int, max_longest_side: int) -> tuple[int, int]:
"""
Calculate a new size preserving aspect ratio so that the longest side
becomes max_longest_side.
"""
longest_side = max(width, height)
if longest_side <= max_longest_side:
return width, height
scale = max_longest_side / float(longest_side)
new_width = max(1, round(width * scale))
new_height = max(1, round(height * scale))
return new_width, new_height
def process_image(src_path: Path, dst_path: Path, max_longest_side: int) -> None:
"""
Resize the image if needed and save it to the destination path.
If no resize is needed, copy the original file.
"""
try:
with Image.open(src_path) as img:
width, height = img.size
new_size = calculate_new_size(width, height, max_longest_side)
if new_size == (width, height):
# Copy unchanged images so the output folder contains all supported files.
shutil.copy2(src_path, dst_path)
print(f"Copied: {src_path.name} ({width}x{height})")
return
resized = img.resize(new_size, Image.Resampling.LANCZOS)
# Preserve PNG transparency if present; convert incompatible modes for JPEG.
if src_path.suffix.lower() in {".jpg", ".jpeg"}:
if resized.mode not in ("RGB", "L"):
resized = resized.convert("RGB")
resized.save(dst_path, quality=95, optimize=True)
else:
resized.save(dst_path, optimize=True)
print(
f"Resized: {src_path.name} "
f"({width}x{height} -> {new_size[0]}x{new_size[1]})"
)
except Exception as exc:
print(f"Error processing '{src_path}': {exc}", file=sys.stderr)
def main() -> int:
"""Program entry point."""
args = parse_args()
input_folder: Path = args.input_folder
if not input_folder.exists():
print(f"Error: Folder does not exist: {input_folder}", file=sys.stderr)
return 1
if not input_folder.is_dir():
print(f"Error: Path is not a directory: {input_folder}", file=sys.stderr)
return 1
output_folder = input_folder / "resized"
output_folder.mkdir(exist_ok=True)
image_files = list(iter_image_files(input_folder))
if not image_files:
print("No supported image files found (.jpg, .jpeg, .png).")
return 0
for src_path in image_files:
dst_path = output_folder / src_path.name
process_image(src_path, dst_path, MAX_LONGEST_SIDE)
print(f"Done. Output saved to: {output_folder}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
```
How to run:
- Install dependency: `pip install Pillow`
- Save the script to a file, for example `resize_images.py`
- Run it with: `python resize_images.py /path/to/your/image_folder`
- Resized and copied images will be written to `/path/to/your/image_folder/resized`
```python
# Requires: pip install Pillow
"""
Image Resizer Script
Scans a folder for .jpg/.jpeg and .png images, resizes any image with longest side > 1920px
to 1920px on the longest side while preserving aspect ratio, and saves copies in a 'resized' subfolder.
"""
from pathlib import Path
from PIL import Image, ImageResampling
import argparse
import os
import sys
def main(input_folder: str) -> None:
"""
Main function to process images in the input folder.
Args:
input_folder: Path to the folder containing images.
"""
input_path = Path(input_folder)
if not input_path.is_dir():
print(f"Error: '{input_folder}' is not a valid directory.", file=sys.stderr)
sys.exit(1)
resized_dir = input_path / 'resized'
resized_dir.mkdir(exist_ok=True)
supported_extensions = {'.jpg', '.jpeg', '.png'}
processed_count = 0
skipped_count = 0
for file_path in input_path.iterdir():
if file_path.is_file() and file_path.suffix.lower() in supported_extensions:
try:
with Image.open(file_path) as img:
width, height = img.size
max_side = max(width, height)
if max_side > 1920:
# Calculate scaling factor to make longest side exactly 1920px
scale = 1920 / max_side
new_width = int(width * scale)
new_height = int(height * scale)
# Resize using Lanczos resampling for high quality
img = img.resize((new_width, new_height), ImageResampling.LANCZOS)
# Determine output path (preserve original filename)
out_path = resized_dir / file_path.name
# Save in appropriate format: PNG preserves transparency, JPEG converts to RGB
if file_path.suffix.lower() == '.png':
img.save(out_path, 'PNG')
else:
# Convert to RGB for JPEG compatibility (handles RGBA PNGs if any)
rgb_img = img.convert('RGB')
rgb_img.save(out_path, 'JPEG', quality=95, optimize=True)
print(f"✓ Processed: {file_path.name} ({width}x{height} -> {img.size if max_side > 1920 else 'unchanged'})")
processed_count += 1
except Exception as e:
print(f"✗ Error processing {file_path.name}: {e}", file=sys.stderr)
skipped_count += 1
print(f"\nSummary: {processed_count} images processed, {skipped_count} skipped due to errors.")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Resize images (>1920px longest side) in a folder to 1920px max side, preserving aspect ratio."
)
parser.add_argument(
"input_folder",
help="Path to the folder containing .jpg/.jpeg/.png images"
)
args = parser.parse_args()
main(args.input_folder)
```
- `pip install Pillow`
- `python script.py /path/to/your/image/folder`
- Resized images saved in `/path/to/your/image/folder/resized/`
- Originals unchanged; script skips non-image files and logs errors
What makes these work
-
01Specify libraries upfront
If you have a preference for pandas over csv, requests over httpx, or argparse over sys.argv, say so in the prompt. Models default to the most common choice, which may not match your environment. Naming your libraries also signals the complexity level you expect and prevents the model from reaching for unnecessary dependencies.
-
02Describe inputs and outputs explicitly
Tell the model what the script receives and what it should produce. Include file names, data formats, and command-line argument structure. A prompt that says 'read a CSV and clean it' is weaker than one that specifies the filename, which columns to act on, and what the output file should be called. Explicit input/output specs eliminate the most common generation errors.
-
03Ask for error handling by default
Generated scripts often skip error handling unless you ask. Add a line like 'include error handling for missing files, bad input, and network failures' to any prompt. This produces code that actually runs in real conditions rather than only on the happy path. It also reduces the back-and-forth needed to make the script production-ready.
-
04Request inline comments for unfamiliar code
If you plan to modify the script or are learning, add 'include comments explaining each major step' to your prompt. This makes the output readable without a separate explanation step and helps you catch logic errors before running the script. For complex scripts, ask the model to describe what each function does at the top of the function.
More example scenarios
Write a Python script that renames all JPEG files in a folder by replacing spaces with underscores and appending the file's last-modified date in YYYY-MM-DD format to the filename. The folder path should be passed as a command-line argument. Print each old and new filename to the console.
A script using os, sys, and datetime modules that iterates over .jpg and .jpeg files in the provided directory, retrieves os.path.getmtime for each file, formats the date, builds the new filename, calls os.rename, and prints a before/after line for each file. Includes a basic check that the directory exists before proceeding.
Write a Python script using pandas that reads a CSV file called sales_data.csv, drops any rows where the 'revenue' column is null or zero, removes duplicate rows based on the 'transaction_id' column, and saves the cleaned data to a new file called sales_data_clean.csv. Print the number of rows removed.
A pandas script that loads the CSV, filters out rows where revenue is null or zero, drops duplicates on transaction_id, calculates original minus final row count, prints that count, and writes the result to sales_data_clean.csv using to_csv with index=False.
Write a Python script that accepts a city name as a command-line argument, calls the OpenWeatherMap current weather API using the requests library, and prints the city name, current temperature in Celsius, weather description, and humidity. Store the API key in an environment variable called OPENWEATHER_API_KEY.
A requests-based script that reads the API key from os.environ, builds the endpoint URL with the city name and units=metric, handles HTTP errors with response.raise_for_status, parses the JSON response, and prints the four requested fields in a readable format with labels.
Write a Python script that watches a log file called app.log and prints any new lines that contain the word ERROR in real time, similar to tail -f. The script should run until manually stopped with Ctrl+C and should handle the case where the file does not exist yet.
A script using a while loop and file seek that opens app.log, moves to the end, then continuously reads new lines, checks if ERROR is in the line, and prints matching lines. Wraps the open call to wait and retry if the file does not exist yet. Catches KeyboardInterrupt cleanly to exit.
Write a Python script using BeautifulSoup and requests that scrapes product names and prices from a static HTML page at a given URL and saves the results to a CSV file called products.csv. Handle cases where a price element might be missing for a product.
A BeautifulSoup script that fetches the page, selects product container elements, extracts the name and price text from each, uses a conditional to insert 'N/A' if the price element is absent, collects results as a list of dicts, and writes them to products.csv using the csv module with headers.
Common mistakes to avoid
-
Prompts that describe a goal, not a task
Writing 'I want to automate my workflow' tells the model nothing actionable. Generated code will be generic and unusable. Describe the exact input, the transformation, and the exact output every time. The more specific your prompt, the less editing the output needs.
-
Running generated code without reading it
AI-generated Python can contain hardcoded paths, missing imports, or logic that silently produces wrong results. Always read through the script before running it, especially if it writes to disk, makes network requests, or handles credentials. Treat generated code as a first draft, not a finished product.
-
Ignoring the model's assumptions
When a prompt is ambiguous, models fill gaps silently. A script might assume a specific CSV column name, a particular file encoding, or a directory structure you do not have. Check the output for hardcoded assumptions and compare them against your actual data before running.
-
Asking for too much in one prompt
A single prompt for a 200-line script with multiple features produces bloated, hard-to-debug code. Break complex tasks into smaller prompts: generate the data-loading function first, then the transformation, then the output. Composing smaller correct pieces is faster than fixing one large broken script.
-
Skipping dependency verification
Generated scripts often import third-party libraries that may not be installed in your environment. Before running, check every import against your installed packages. A script that imports pandas when you have an older version, or requests when you are using httpx, will fail immediately with an import error that is easy to prevent.
Related queries
Frequently asked questions
Which AI model is best for generating Python scripts from text prompts?
It depends on the complexity of the task. GPT-4o and Claude 3.5 Sonnet both handle multi-step data processing and API integration scripts well. For short utility scripts, almost any capable model works. The comparison table on this page shows how each model handled the same prompt, which is more useful than a general ranking.
Can I generate a Python script from a prompt without knowing how to code?
Yes, but you need to be specific about what the script should do. The less you know about Python, the more precise your plain-English description needs to be, because you cannot catch errors in the output as easily. Start with small, well-defined tasks and test each script before building on it.
How do I make sure the generated Python script actually runs?
Read through the output before executing it. Check that all imported libraries are installed, that any file paths or credentials match your environment, and that the script handles edge cases like missing files or empty data. Running in a virtual environment and testing on a small sample first reduces risk significantly.
What is the best way to prompt an AI to write Python code?
State the input, the transformation, and the output in plain language. Specify any libraries you want used. Mention error handling, command-line arguments, and output format explicitly. The more detail you include about what the script should do and what environment it will run in, the more usable the output will be.
Can AI generate Python scripts that work with my existing codebase?
Only if you provide context about that codebase in the prompt. Paste in the relevant function signatures, class definitions, or data structures and ask the model to generate code that integrates with them. Without that context, the model generates standalone code that may conflict with your existing patterns and conventions.
Is AI-generated Python code safe to use in production?
Not without review. Generated code frequently skips input validation, may use insecure patterns for handling credentials or user data, and may not follow your team's standards. Treat it as a starting point that needs code review, testing, and security checks before it goes anywhere near a production environment.
Try it with a real tool
Run this prompt in one of these tools. Affiliate links help keep Gridlyx free.