Run one prompt across a whole folder of files
Send the same AI prompt to every text file in a folder automatically, without opening them one by one.
Opening the same prompt once for every file in a folder is slow. If you have twenty text files, you copy and paste twenty times. This article shows how to send one prompt to every file automatically.
Gather your files
- Create a folder called
input. - Copy the text files you want to process into it.
- Create an empty folder called
outputnext to it.
The script reads each file from input, sends it to the AI, and saves the answer in output.
Reference: Python pathlib documentation
Install the library
- Open a terminal or command prompt.
- Run this command:
pip install openai
This installs the OpenAI Python library, which lets your script send messages to the AI service.
Reference: OpenAI quickstart
Store your API key
An API key is a secret password that lets your code talk to the AI service. An environment variable is a stored value your computer remembers for programs. Save the key as an environment variable so you do not paste it into the script.
- On macOS or Linux, run:
export OPENAI_API_KEY="your-key-here"
- On Windows PowerShell, run:
$env:OPENAI_API_KEY="your-key-here"
Replace your-key-here with your actual key.
Reference: OpenAI API authentication
Write the script
- Save this code as
batch_prompt.pyin the folder that containsinputandoutput.
import os
from pathlib import Path
from openai import OpenAI
client = OpenAI()
prompt = "Summarise this file in three bullet points:"
input_folder = Path("input")
output_folder = Path("output")
output_folder.mkdir(exist_ok=True)
for file_path in input_folder.glob("*.txt"):
text = file_path.read_text(encoding="utf-8")
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": prompt + "\n\n" + text}
],
)
answer = response.choices[0].message.content
(output_folder / file_path.name).write_text(answer, encoding="utf-8")
- Edit the text after
prompt =if you want a different instruction.
A loop repeats the same action for each file in a list. UTF-8 is a way computers store text so accents and symbols appear correctly. It is like giving one assistant a stack of letters and asking the same question about each letter.
Reference: OpenAI chat completions documentation
Run it
- Run this command:
python batch_prompt.py
Expected result:
A new set of files appears inside output. Each file matches one file in input and contains the AI’s answer to your prompt.
Sources
Stay Ahead. Work Smarter.
Get practical AI tips, automation ideas and useful technology tricks — one useful thing at a time. Follow the feed in any reader.