From Idea to Automation: 12 Python Prompts That Write Your Scripts While You Sip Coffee
You’ve been there: a repetitive task eats your afternoon — renaming 200 files, scraping a dozen web pages, cleaning a messy CSV. You know Python could do it in minutes, but writing the script from scratch feels like a project in itself. What if you could describe the task in plain English and get a working script in seconds? That’s the promise of AI-assisted coding, and with the right prompts, you can turn natural language into production‑ready Python.
This guide isn’t about theory. It’s a practical collection of 12 prompts that I use daily to automate file operations, data munging, web scraping, API integrations, and even script refactoring. Each prompt is battle‑tested, includes a concrete example, and estimates the time you’ll save compared to writing the code manually. Whether you’re a data analyst, a DevOps engineer, or a hobbyist, these prompts will become your secret weapon.
Why Prompts Beat Blank‑Page Coding
Generative AI models like GPT‑4 have been trained on vast amounts of Python code. When you give them a clear, specific prompt, they can produce syntactically correct, efficient scripts that handle edge cases you might have missed. According to a 2023 study by GitHub, developers using AI pair programmers completed tasks 55% faster (source: GitHub Blog). While that statistic is about Copilot, the principle applies to any AI coding assistant.
But a vague prompt yields vague code. The secret lies in prompt engineering: being explicit about inputs, outputs, libraries, and error handling. Below, I’ve curated 12 prompts that cover the most common automation scenarios, each with a real‑world example and a clear “why it works.”
The Prompts
1. File Renaming with Regex
Task: Write a Python script to rename files in a folder based on a pattern, using regex for flexibility.
Prompt:
You are an expert Python developer. Write a script that renames all files in a given directory. The script should accept the directory path, a regex pattern to match the current filename, and a replacement string. It should also support a dry-run mode that prints the changes without applying them. Use only the standard library. Include error handling for non-existent directories and permission issues.
Example Output:
import os
import re
import sys
def rename_files(directory, pattern, replacement, dry_run=True):
if not os.path.isdir(directory):
raise FileNotFoundError(f"Directory not found: {directory}")
for filename in os.listdir(directory):
new_name = re.sub(pattern, replacement, filename)
if new_name != filename:
old_path = os.path.join(directory, filename)
new_path = os.path.join(directory, new_name)
if dry_run:
print(f"[DRY RUN] {filename} -> {new_name}")
else:
os.rename(old_path, new_path)
print(f"Renamed: {filename} -> {new_name}")
if __name__ == "__main__":
# Example usage: python rename.py /path/to/files '\s+' '_' --apply
import argparse
parser = argparse.ArgumentParser(description="Rename files using regex")
parser.add_argument("directory", help="Directory containing files")
parser.add_argument("pattern", help="Regex pattern to match")
parser.add_argument("replacement", help="Replacement string")
parser.add_argument("--apply", action="store_true", help="Actually rename files")
args = parser.parse_args()
rename_files(args.directory, args.pattern, args.replacement, dry_run=not args.apply)
Why it saves time: Writing a robust renaming script with dry-run and error handling from scratch takes ~30 minutes. This prompt gets you there in under a minute.
2. CSV Cleaning and Standardization
Task: Write a script to clean a CSV file: handle missing values, strip whitespace, convert date formats, and remove duplicates.
Prompt:
Write a Python script using pandas to clean a CSV file. The script should:
- Read a CSV file (path provided).
- Strip whitespace from all string columns.
- Convert date columns to ISO format (YYYY-MM-DD).
- Fill missing numeric values with the column mean.
- Remove duplicate rows based on all columns.
- Output the cleaned data to a new CSV file.
Provide a command-line interface using argparse.
Example Output:
import pandas as pd
import argparse
from datetime import datetime
def clean_csv(input_path, output_path):
df = pd.read_csv(input_path)
# Strip whitespace
for col in df.select_dtypes(include='object').columns:
df[col] = df[col].str.strip()
# Convert dates (assume 'date' column)
if 'date' in df.columns:
df['date'] = pd.to_datetime(df['date'], errors='coerce').dt.strftime('%Y-%m-%d')
# Fill missing numeric with mean
for col in df.select_dtypes(include='number').columns:
df[col].fillna(df[col].mean(), inplace=True)
# Drop duplicates
df.drop_duplicates(inplace=True)
df.to_csv(output_path, index=False)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('input', help='Input CSV path')
parser.add_argument('output', help='Output CSV path')
args = parser.parse_args()
clean_csv(args.input, args.output)
Why it saves time: Cleaning a messy CSV manually in pandas takes 45–60 minutes. This prompt delivers a reusable script instantly.
3. Web Scraping with BeautifulSoup
Task: Write a script to scrape product prices from a static e-commerce page.
Prompt:
Write a Python script using requests and BeautifulSoup to scrape product names and prices from a given URL. The page uses HTML classes 'product-name' and 'product-price'. Handle network errors gracefully, and save the results to a CSV file. Include a polite delay between requests if scraping multiple pages.
Example Output:
import requests
from bs4 import BeautifulSoup
import csv
import time
def scrape_products(url):
headers = {'User-Agent': 'Mozilla/5.0'}
try:
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(f"Error fetching {url}: {e}")
return []
soup = BeautifulSoup(response.text, 'html.parser')
products = []
for name_elem, price_elem in zip(soup.select('.product-name'), soup.select('.product-price')):
name = name_elem.get_text(strip=True)
price = price_elem.get_text(strip=True)
products.append({'name': name, 'price': price})
return products
def save_to_csv(products, filename):
with open(filename, 'w', newline='', encoding='utf-8') as f:
writer = csv.DictWriter(f, fieldnames=['name', 'price'])
writer.writeheader()
writer.writerows(products)
# Example usage
if __name__ == '__main__':
url = "https://example.com/products"
products = scrape_products(url)
save_to_csv(products, "products.csv")
print(f"Saved {len(products)} products")
Why it saves time: Writing a scraper with error handling and CSV output takes 1–2 hours. This prompt gives you a solid foundation in minutes.
4. Sending Automated Emails
Task: Write a script to send personalized emails to a list of recipients from a CSV.
Prompt:
Write a Python script that reads a CSV file with columns 'email', 'name', and 'message', and sends a personalized email to each recipient using SMTP. Use environment variables for SMTP credentials. Support attachments if a file path is provided. Use the 'email' and 'smtplib' libraries. Include error handling for connection failures.
Example Output:
import smtplib
import csv
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_emails(csv_path, smtp_server, smtp_port, username, password, attachment=None):
with open(csv_path, 'r', encoding='utf-8') as f:
reader = csv.DictReader(f)
for row in reader:
to_email = row['email']
subject = "Your personalized subject"
body = f"Dear {row['name']},\n\n{row['message']}"
msg = MIMEMultipart()
msg['From'] = username
msg['To'] = to_email
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
# Add attachment if provided
if attachment:
from email.mime.base import MIMEBase
from email import encoders
with open(attachment, 'rb') as f:
part = MIMEBase('application', 'octet-stream')
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename={os.path.basename(attachment)}')
msg.attach(part)
try:
with smtplib.SMTP(smtp_server, smtp_port) as server:
server.starttls()
server.login(username, password)
server.sendmail(username, to_email, msg.as_string())
print(f"Sent to {to_email}")
except Exception as e:
print(f"Failed to send to {to_email}: {e}")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('csv_path')
parser.add_argument('--smtp-server', default='smtp.gmail.com')
parser.add_argument('--smtp-port', type=int, default=587)
parser.add_argument('--username', default=os.getenv('SMTP_USER'))
parser.add_argument('--password', default=os.getenv('SMTP_PASS'))
parser.add_argument('--attachment')
args = parser.parse_args()
send_emails(args.csv_path, args.smtp_server, args.smtp_port, args.username, args.password, args.attachment)
Why it saves time: Setting up SMTP, MIME, and error handling typically takes 1–2 hours. This prompt condenses that to seconds.
5. Automating Excel Reports
Task: Write a script to generate an Excel report with charts from a CSV.
Prompt:
Write a Python script using openpyxl or pandas to generate an Excel report from a CSV file. The report should include:
- A summary sheet with key statistics (mean, median, count).
- A chart showing sales over time.
- Formatting: bold headers, autofit column widths.
Use pandas and openpyxl. Provide a command-line interface.
Example Output:
import pandas as pd
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.chart import LineChart, Reference
# Load data
csv_file = "sales.csv"
df = pd.read_csv(csv_file, parse_dates=['date'])
# Create workbook
wb = Workbook()
ws = wb.active
ws.title = "Summary"
# Add summary stats
stats = df.describe()
for r in dataframe_to_rows(stats, index=True, header=True):
ws.append(r)
# Add chart sheet
ws_chart = wb.create_sheet("Chart")
# Assuming columns: date and sales
for r in dataframe_to_rows(df[['date', 'sales']], index=False, header=True):
ws_chart.append(r)
chart = LineChart()
chart.title = "Sales Over Time"
data = Reference(ws_chart, min_col=2, min_row=1, max_row=len(df)+1)
dates = Reference(ws_chart, min_col=1, min_row=2, max_row=len(df)+1)
chart.add_data(data, titles_from_data=True)
chart.set_categories(dates)
ws_chart.add_chart(chart, "D2")
# Formatting: bold headers
for cell in ws[1]:
cell.font = Font(bold=True)
wb.save("report.xlsx")
Why it saves time: Creating a formatted Excel report with charts manually takes 1.5–2 hours. This script is ready in minutes.
6. Data Visualization from CSV
Task: Write a script to create multiple plots from a CSV using matplotlib.
Prompt:
Write a Python script that reads a CSV file and creates a 2x2 grid of plots: histogram of a numeric column, scatter plot of two columns, bar chart of a categorical column, and a line chart of time series. Use matplotlib. Save the figure as PNG.
Example Output:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('data.csv')
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
# Histogram
axes[0,0].hist(df['numeric_col'].dropna(), bins=20)
axes[0,0].set_title('Histogram')
# Scatter
axes[0,1].scatter(df['x_col'], df['y_col'])
axes[0,1].set_title('Scatter')
# Bar chart
axes[1,0].bar(df['cat_col'].value_counts().index, df['cat_col'].value_counts().values)
axes[1,0].set_title('Bar Chart')
# Line chart
axes[1,1].plot(df['date'], df['value'])
axes[1,1].set_title('Time Series')
plt.tight_layout()
plt.savefig('report.png')
Why it saves time: Exploratory plotting is iterative; this boilerplate saves 30–45 minutes.
7. REST API Integration
Task: Write a script to fetch data from a REST API and store it in a database.
Prompt:
Write a Python script using requests that fetches data from a REST API endpoint (e.g., https://api.example.com/items) with pagination. For each item, insert or update a record in a SQLite database using sqlite3. Handle API rate limits by sleeping between requests. Include basic error handling and logging.
Example Output:
import requests
import sqlite3
import time
import logging
logging.basicConfig(level=logging.INFO)
def fetch_items(base_url, api_key=None):
headers = {'Authorization': f'Bearer {api_key}'} if api_key else {}
page = 1
conn = sqlite3.connect('items.db')
c = conn.cursor()
c.execute('CREATE TABLE IF NOT EXISTS items (id INTEGER PRIMARY KEY, name TEXT, price REAL)')
while True:
params = {'page': page, 'per_page': 100}
try:
resp = requests.get(base_url, headers=headers, params=params, timeout=10)
resp.raise_for_status()
except requests.exceptions.RequestException as e:
logging.error(f"Request failed: {e}")
break
data = resp.json()
if not data:
break
for item in data:
c.execute('INSERT OR REPLACE INTO items (id, name, price) VALUES (?, ?, ?)',
(item['id'], item['name'], item['price']))
conn.commit()
logging.info(f"Fetched page {page}")
page += 1
time.sleep(1) # rate limit
conn.close()
if __name__ == '__main__':
fetch_items('https://api.example.com/items', api_key='your_key')
Why it saves time: API integration with pagination and database storage is a classic task taking 1–3 hours.
8. Automating File Backup
Task: Write a script to backup files from a directory to a remote server via SFTP.
Prompt:
Write a Python script that backs up all files from a local directory to a remote server via SFTP using paramiko. The script should:
- Accept local directory, remote path, hostname, username, and password via command-line arguments.
- Create a timestamped subdirectory on the remote server.
- Upload all files, skipping files that already exist (by size).
- Log each action.
Example Output:
import paramiko
import os
import sys
import logging
import argparse
def backup(local_dir, remote_base, host, username, password):
logging.basicConfig(level=logging.INFO)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host, username=username, password=password)
sftp = ssh.open_sftp()
timestamp = time.strftime('%Y%m%d_%H%M%S')
remote_dir = f"{remote_base}/{timestamp}"
try:
sftp.mkdir(remote_dir)
except IOError:
pass
for root, dirs, files in os.walk(local_dir):
for file in files:
local_path = os.path.join(root, file)
remote_path = os.path.join(remote_dir, os.path.relpath(local_path, local_dir))
# Ensure remote subdir exists
sftp.mkdir(os.path.dirname(remote_path))
# Upload if different size
try:
remote_size = sftp.stat(remote_path).st_size
except IOError:
remote_size = -1
if remote_size != os.path.getsize(local_path):
sftp.put(local_path, remote_path)
logging.info(f"Uploaded {file}")
sftp.close()
ssh.close()
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('local_dir')
parser.add_argument('remote_base')
parser.add_argument('--host', required=True)
parser.add_argument('--username', required=True)
parser.add_argument('--password', required=True)
args = parser.parse_args()
backup(args.local_dir, args.remote_base, args.host, args.username, args.password)
Why it saves time: SFTP backup scripts often require troubleshooting, but this prompt handles the tricky parts.
9. PDF Text Extraction
Task: Write a script to extract text from a PDF file and save it as a text file.
Prompt:
Write a Python script using PyPDF2 or pdfplumber to extract text from a PDF file. The script should accept input and output file paths as arguments. Handle encrypted PDFs by asking for a password. Preserve page breaks.
Example Output:
import PyPDF2
import sys
def extract_text(input_pdf, output_txt, password=None):
with open(input_pdf, 'rb') as f:
reader = PyPDF2.PdfFileReader(f)
if reader.isEncrypted:
if password:
reader.decrypt(password)
else:
print("PDF is encrypted. Provide password.")
return
text = ""
for page in reader.pages:
text += page.extract_text() + "\n"
with open(output_txt, 'w', encoding='utf-8') as f:
f.write(text)
print(f"Extracted {len(text)} characters")
if __name__ == '__main__':
if len(sys.argv) < 3:
print("Usage: python extract_pdf.py input.pdf output.txt [password]")
sys.exit(1)
input_pdf = sys.argv[1]
output_txt = sys.argv[2]
password = sys.argv[3] if len(sys.argv) > 3 else None
extract_text(input_pdf, output_txt, password)
Why it saves time: PDF extraction is fiddly; PyPDF2 setup takes ~20 minutes.
10. Automating Excel Data Entry
Task: Write a script to read data from a web form and populate an Excel spreadsheet.
Prompt:
Write a Python script that uses Selenium to scrape data from a web form after submitting it, and writes the results to an Excel file. The form has fields 'username' and 'password'. After login, scrape a table with class 'results-table'. Use openpyxl to save the data.
Example Output:
from selenium import webdriver
from selenium.webdriver.common.by import By
import openpyxl
import time
driver = webdriver.Chrome()
driver.get('https://example.com/login')
username = driver.find_element(By.NAME, 'username')
username.send_keys('your_username')
password = driver.find_element(By.NAME, 'password')
password.send_keys('your_password')
password.submit()
time.sleep(5)
table = driver.find_element(By.CLASS_NAME, 'results-table')
rows = table.find_elements(By.TAG_NAME, 'tr')
data = []
for row in rows:
cells = row.find_elements(By.TAG_NAME, 'td')
data.append([cell.text for cell in cells])
driver.quit()
wb = openpyxl.Workbook()
ws = wb.active
for row in data:
ws.append(row)
wb.save('results.xlsx')
Why it saves time: Selenium scripts are notoriously verbose; this prompt cuts development time from 2 hours to 10 minutes.
11. Refactoring Legacy Code with AI
Task: Refactor an existing script to use best practices.
Prompt:
Refactor the following Python script to improve readability, add type hints, and use context managers. Preserve functionality. The script is: [paste code].
Example Output:
Before:
def process(data):
result = []
for i in data:
if i % 2 == 0:
result.append(i*2)
return result
After:
from typing import List
def process(data: List[int]) -> List[int]:
"""Return doubled even numbers."""
return [i * 2 for i in data if i % 2 == 0]
Why it saves time: Manual refactoring of large scripts can take hours; AI can do it in seconds, but review is still needed.
12. Generating Unit Tests
Task: Write unit tests for a given function.
Prompt:
Write a set of unittest tests for the following function that checks edge cases, including empty input, type errors, and boundary conditions. The function is: [paste code].
Example Output:
import unittest
class TestProcess(unittest.TestCase):
def test_empty_list(self):
self.assertEqual(process([]), [])
def test_even_numbers(self):
self.assertEqual(process([1,2,3,4]), [4,8])
def test_negative_numbers(self):
self.assertEqual(process([-2, -1, 0, 1]), [-4, 0])
def test_type_error(self):
with self.assertRaises(TypeError):
process("not a list")
if __name__ == '__main__':
unittest.main()
Why it saves time: Writing comprehensive test cases is tedious; this prompt gives a solid starting point.
Putting It All Together: A Real‑World Workflow
Imagine you receive a daily CSV report, need to clean it, visualize trends, and email the summary to your boss. Instead of writing three separate scripts, you can combine the prompts:
- Use Prompt #2 to clean the CSV.
- Use Prompt #6 to generate charts.
- Use Prompt #4 to email the charts.
Each prompt is designed to be modular, so you can chain them into a pipeline. For a more advanced approach, wrap them in a single Python script that calls functions from each module.
The Bottom Line
AI‑assisted coding isn’t about replacing your skills — it’s about accelerating them. By using structured prompts, you can generate reliable Python scripts for routine tasks, freeing up time for creative problem‑solving. The 12 prompts above cover the most common automation scenarios, but the true power lies in adapting them to your unique needs.
Next time you face a repetitive task, don’t start from a blank file. Open your AI assistant, paste a tailored prompt, and watch as a working script materializes. Your coffee will still be warm.
What’s your favourite automation prompt? Share it in the comments below — I’m always looking to expand my toolbox.
Comments