October 15, 2026

AI Python Scripts: Automate Files, CSVs and Reports

AI Python scripts cover with a dotted grid background and a blue underline beneath the title

AI Python scripts are the quickest way for a non-programmer, or a busy one, to automate boring computer work: renaming hundreds of files, merging and cleaning CSV exports, or producing the same monthly report without copying numbers by hand. You describe the job in plain language, the assistant writes the script, and you run it on a copy of your data. The skill is not typing code. It is describing the task precisely and checking what the script does before it touches anything important.

This guide shows how to get safe, working AI Python scripts for everyday office automation. It covers how to brief the assistant, three complete examples, safety habits such as dry runs and backups, how to read a script you did not write, and when a script is the wrong tool.

What makes a good task for a Python script

Python is well suited to jobs that are repetitive, rule-based and done on files or tables. If you can explain the steps to a new colleague in a few sentences, a script can probably do them.

Good candidates

  • Renaming, sorting or moving files by date, type or a pattern in the name.
  • Merging several spreadsheets or CSV files into one.
  • Cleaning columns: trimming spaces, fixing date formats, removing duplicates.
  • Producing a summary table or chart from a data file every week.
  • Extracting text or numbers from a folder of similar documents.
  • Checking a list of links or file names against a rule.

Poor candidates

  • Jobs that need judgement on every item, such as deciding which e-mails matter.
  • Anything that deletes or overwrites the only copy of important data.
  • Tasks involving other people’s accounts or passwords.
  • One-off jobs that take five minutes by hand.

How to brief the assistant for AI Python scripts

Vague requests produce vague code. A good brief has six parts, and you can reuse the same shape every time.

  1. Goal. One sentence describing the result.
  2. Input. Folder or file names, columns, and two or three sample rows with fake or sanitised values.
  3. Output. What the script should create, and where.
  4. Rules. Every edge case you can think of: what to do with blanks, duplicates, missing files.
  5. Safety. “Never delete or overwrite originals. Show what would happen first.”
  6. Environment. Operating system, Python version if you know it, and whether you may install extra packages.

Ask for explanations too: “Explain each block in one sentence so I can check it.” Our general guide to AI code generation covers the habits that apply to every language.

Example 1: rename files safely

Imagine a folder of scanned receipts called IMG_0412.jpg and similar. You want them renamed to start with the year and month of the file’s modified date. The brief might be: “Write a Python script that renames .jpg files in a folder to YYYY-MM_originalname.jpg using the modified date. Run in preview mode by default and only rename when I pass –apply. Never overwrite an existing file.”

from pathlib import Path
from datetime import datetime
import sys

folder = Path(sys.argv[1])
apply = "--apply" in sys.argv

for f in sorted(folder.glob("*.jpg")):
    stamp = datetime.fromtimestamp(f.stat().st_mtime).strftime("%Y-%m")
    new = f.with_name(f"{stamp}_{f.name}")
    if new.exists():
        print("SKIP (exists):", new.name)
        continue
    print(f.name, "->", new.name)
    if apply:
        f.rename(new)

What to notice

  • The script prints the plan first and only changes files when you add --apply.
  • It skips a name that already exists instead of overwriting it.
  • It uses the standard pathlib module, so no extra packages are needed.

Run it on a copy of the folder first. If the preview looks right, run it with --apply on the real folder.

Example 2: clean and merge CSV exports

Suppose you receive a monthly sales export as several CSV files with slightly different headers, trailing spaces and duplicate rows. The brief: “Merge all CSV files in a folder into one file. Trim spaces in text columns, parse the date column, remove exact duplicate rows and save the result as merged.csv. Print how many rows were read and kept.”

from pathlib import Path
import pandas as pd

files = sorted(Path("exports").glob("*.csv"))
frames = [pd.read_csv(f) for f in files]
df = pd.concat(frames, ignore_index=True)
read = len(df)

df.columns = [c.strip().lower() for c in df.columns]
for col in df.select_dtypes(include="object"):
    df[col] = df[col].str.strip()
df["date"] = pd.to_datetime(df["date"], errors="coerce")
df = df.drop_duplicates()

df.to_csv("merged.csv", index=False)
print("read", read, "rows, kept", len(df))

Questions to ask before trusting it

  • What happens to rows where the date cannot be parsed? Here they become blank values, which you should count and inspect.
  • Are columns spelled the same in every file? If not, ask for a mapping step.
  • Does it modify the originals? This one only reads them.

The script relies on the widely used pandas library. If you are only reading simple files, the built-in csv module also works. For deeper analysis of the cleaned file, see our guide to the AI data analysis assistant.

Example 3: a repeatable report

The third example summarises sales by product for the month and draws a chart. The brief: “Read merged.csv, calculate total amount per product for the latest month, save a table as summary.csv and a bar chart as summary.png.”

import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

df = pd.read_csv("merged.csv", parse_dates=["date"])
latest = df["date"].dt.to_period("M").max()
month = df[df["date"].dt.to_period("M") == latest]

summary = (month.groupby("product")["amount"].sum()
           .sort_values(ascending=False).reset_index())
summary.to_csv("summary.csv", index=False)

ax = summary.plot.bar(x="product", y="amount", legend=False)
ax.set_title(f"Sales by product, {latest}")
plt.tight_layout()
plt.savefig("summary.png", dpi=150)
print(summary.head())

Once it works, you can run it every month in seconds. If you want the assistant to run code for you rather than run it yourself, plans with Code mode include a code execution sandbox; our article on the Python sandbox explains what it can and cannot do.

Working with Ask Mio on a script

A script is rarely right on the first try, so treat the work as a short conversation. In Ask Mio, Code mode routes the request to a model suited to code, and the Senior developer expert can be switched on for the whole chat if you want explanations aimed at a beginner. A typical session has four turns.

  1. Brief and first draft. Paste the six-part brief and ask for the script with block-by-block comments.
  2. Review. Ask Mio to list everything the script reads, writes and deletes, and to name any assumption it made.
  3. Test and report. Run it on a copy, then paste the output or the error back.
  4. Harden. Ask for checks on missing files, empty values and wrong formats, plus a log file.

A coding answer costs roughly 5 to 10 points, so a four-turn session is a modest use of a monthly allowance. Keep the script and the brief together in a project, so that next month you can ask for a small change instead of starting from zero.

Safety habits for any script you did not write

A script can do real damage in a second. These habits cost almost nothing.

Habit Why it matters How to apply it
Work on a copy A bug cannot harm the original Copy the folder or file before the first run
Preview first You see changes before they happen Ask for a dry-run mode that only prints
Read the imports Reveals unexpected network or system access Be wary of unfamiliar packages and of requests or subprocess calls you did not ask for
Search for delete and overwrite Finds destructive operations Look for remove, unlink, rmtree and write modes
Test on a tiny sample Catches wrong assumptions quickly Run on three files or ten rows first
Keep a log Lets you undo and audit Ask the script to write what it did to a text file
Never paste secrets Keys and passwords may be stored or shared Use placeholders and environment variables

How to read a script you did not write

You do not need to know Python to review one. Ask the assistant to walk you through it, then check these things yourself.

  1. Find the inputs. Which folders, files or columns does it read?
  2. Find the outputs. What does it create, rename or delete?
  3. Look for loops. A loop over files is where large effects happen.
  4. Look for hard-coded values. Paths and column names you did not mention are red flags.
  5. Run it small. If the result on three files surprises you, stop and ask why.

When things go wrong, paste the full error message and the relevant lines back to the assistant, as described in our guide on debugging code from an error message. For wider warnings about generated code, read when not to trust AI-generated code.

Running scripts on a schedule

After a script works by hand, you may want it to run automatically, for example every Monday. On Windows this is done with Task Scheduler, and on macOS and Linux with cron or launchd. Ask the assistant for step-by-step instructions for your system and for a script that writes a log file, so you can see when something fails. Do not schedule a script until you have run it manually several times on real data and checked the output.

Scheduled scripts also need maintenance. Folder names change, columns are renamed and software updates alter behaviour. Check the log once a month, and keep a note of what the script does and who owns it, so that it does not become a mystery job that nobody dares to touch.

When a script is the wrong tool

If the job changes every time, needs human judgement, or touches systems where mistakes are costly, a script may add risk. Spreadsheet formulas often handle simple tasks with less overhead, and our guide to AI for spreadsheets compares the options. For terminal tasks that are better done with shell commands, see AI Bash script generator.

Frequently Asked Questions

Can I use AI Python scripts without knowing Python?

Yes, for simple jobs, if you are careful. Describe the task precisely, ask the assistant to explain each block, run the script on a copy of your data and check the output. As you repeat the process you will start to understand the code, which makes problems easier to spot.

Is it safe to run code written by an AI?

It is as safe as code from any stranger: review it first. Read what it imports, what files it touches and whether it deletes or overwrites anything. Use a dry-run mode, test on a copy and avoid scripts that make network requests you did not ask for.

Which tasks are best for a first script?

Start with something low-risk that you can verify by eye, such as listing files, renaming copies or merging two small CSV files. These jobs show quickly whether the script does what you meant, and a mistake costs little because you work on copies.

Do I need to install anything?

You need Python on your computer, and pandas or matplotlib for the table and chart examples. The first example uses only built-in modules. Ask the assistant for installation steps for your operating system, and for a version that avoids extra packages if you prefer.

Can Ask Mio run the code for me?

Plans with Code mode include a code execution sandbox that runs Python or Node code, and Mio can use it to compute results, analyse a table or draw a chart. Files on your own computer are not touched, so for renaming local files you still run the script yourself.

What if the script gives a wrong result?

Do not trust it just because it ran without errors. Compare the output with a manual calculation on a few rows, then give the assistant the input, the expected result and the actual result. Ask it to find the cause, and add a test or print statement that would have caught the problem.

The Bottom Line

AI Python scripts let you automate file, CSV and report work without becoming a developer, provided you write a precise brief, ask for a preview mode, test on copies and read what the script does. Begin with a small, low-risk task and build up. To get your first script drafted and explained, start with Ask Mio’s free plan, or choose a plan with Code mode to run code in a sandbox.


Try Ask Mio free

Free plan, no card required.

Start free