Python Script Prompt for Quick Automation
A structured prompt that writes a working, commented Python script for your task — with error handling and a real example output.
Enhanced prompt — ready to use
ROLE You are a senior Python developer with expertise in writing efficient and clear scripts. Your goal is to create a Python script fulfilling the user's requirements. TASK Write a Python script based on the described purpose or functionality. Think through this step by step, considering potential edge cases and ensuring code clarity. CONTEXT The user requests a Python script but has not specified the script's intended use or functionality. The script should be general-purpose but can be adapted as needed once more details are provided. REQUIREMENTS - Write clean, well-documented Python code following best practices. - Think step by step. Consider edge cases that might affect the script’s performance or correctness. - Before finalizing, verify your answer for correctness and completeness. - Assumptions: Since no specific functionality is provided, assume a simple example script demonstrating core Python features. OUTPUT FORMAT Provide the Python script in a single, complete code block with comments explaining key parts.
That's what PromptAI produced from this vague prompt: “write a python script”
Example result
```python
#!/usr/bin/env python3
"""
A general-purpose Python script demonstrating core Python features,
including command-line argument parsing, file operations, error handling,
logging, and basic data processing.
This script reads a text file, counts the occurrences of each word,
and writes the results to an output file.
Usage:
python wordcount.py input.txt output.txt
If no arguments are provided, it uses default sample text.
"""
import sys
import os
import string
import logging
from collections import Counter
def setup_logging():
"""Configure logging to output debug information to the console."""
logging.basicConfig(
level=logging.DEBUG,
format='%(levelname)s:%(message)s'
)
def normalize_word(word):
"""
Normalize a word by lowercasing and stripping punctuation.
Args:
word (str): The word to normalize.
Returns:
str: The normalized word.
"""
return word.strip(string.punctuation).lower()
def count_words(text):
"""
Count occurrences of each word in the given text.
Args:
text (str): Input text to process.
Returns:
collections.Counter: Dictionary-like object with word counts.
"""
words = text.split()
normalized_words = [normalize_word(w) for w in words if normalize_word(w)]
word_counts = Counter(normalized_words)
logging.debug(f"Counted {len(word_counts)} unique words.")
return word_counts
def read_file(filepath):
"""
Read the entire content of a file.
Args:
filepath (str): Path to the file.
Returns:
str: The content of the file.
Raises:
IOError: If the file cannot be read.
"""
logging.debug(f"Reading from file: {filepath}")
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
return content
def write_word_counts(word_counts, filepath):
"""
Write word counts to a file, one word per line with count.
Args:
word_counts (Counter): Word counts to write.
filepath (str): Output file path.
Raises:
IOError: If the file cannot be written.
"""
logging.debug(f"Writing word counts to file: {filepath}")
with open(filepath, 'w', encoding='utf-8') as f:
for word, count in word_counts.most_common():
f.write(f"{word}\t{count}\n")
def main(input_path=None, output_path=None):
"""
Main function to execute word counting.
Args:
input_path (str or None): Path to the input text file.
output_path (str or None): Path to the output results file.
"""
setup_logging()
# Sample fallback text if no input file is provided
sample_text = (
"This is a sample text. It contains words, some of which repeat. "
"Sample text is useful to demonstrate word counting."
)
# Read input text
if input_path:
if not os.path.isfile(input_path):
logging.error(f"Input file does not exist: {input_path}")
sys.exit(1)
try:
text = read_file(input_path)
except IOError as e:
logging.error(f"Failed to read input file: {e}")
sys.exit(1)
else:
logging.info("No input file provided; using sample text.")
text = sample_text
# Count words
word_counts = count_words(text)
# Write output
if output_path:
try:
write_word_counts(word_counts, output_path)
logging.info(f"Word counts written to {output_path}")
except IOError as e:
logging.error(f"Failed to write output file: {e}")
sys.exit(1)
else:
# If no output path provided, print counts to stdout
logging.info("No output file provided; printing results.")
for word, count in word_counts.most_common():
print(f"{word}\t{count}")
if __name__ == "__main__":
# Parse command line arguments
# Expected usage: python script.py [input_file] [output_file]
input_file = sys.argv[1] if len(sys.argv) > 1 else None
output_fileHow to adapt it
- •Describe the input, output, and any libraries you want it to use or avoid.
- •Ask for inline comments and a usage example so it's easy to run.
Have your own rough prompt? Enhance it into a structured prompt like this in one click.
Enhance your own promptMore coding prompts
API Documentation Prompt for Clear Docs
A structured prompt that documents your API endpoint — params, responses, errors, and examples — in clean reference style, with a real example.
Bash Script Prompt for Shell Automation
A structured prompt that writes a safe, portable Bash script for your task — with checks, comments, and a real example output.
Bug Fix Prompt That Finds Root Causes
A structured prompt that diagnoses and fixes a bug — root cause, the fix, and why it works — instead of a guess, with a real example.
Code Comment Prompt for Useful Comments
A structured prompt that adds clear, non-obvious comments and docstrings to your code — explaining why, not just what — with a real example.
Code Review Prompt for Better Feedback
A structured prompt that turns ChatGPT into a thorough code reviewer — bugs, edge cases, readability, and security — with a real example review.
Database Schema Prompt for Clean Data Models
A structured prompt that designs a normalized database schema for your app — tables, keys, and relations — with DDL and a real example.