CodingNic

Files, Errors, and Automation

Simple Automation Scripts

Files, Errors, and Automation 30 min read

Simple Automation Scripts

Simple Automation Scripts

Automation means using code to do repeated work for you.

Instead of doing the same task by hand again and again, Python can do it automatically.

What Is Automation?

Automation is when a program completes tasks with little or no manual work.

Examples:

  • Rename many files
  • Move files into folders
  • Create backups
  • Read reports
  • Save logs
  • Clean old files

Why Automation Matters

Automation helps you:

  • Save time
  • Reduce mistakes
  • Handle many files quickly
  • Repeat tasks easily

Example 1: Auto Backup File

Copy one file into a backup folder.

python
import shutil
import os

if not os.path.exists("backup"):
    os.mkdir("backup")

shutil.copy("notes.txt", "backup/notes.txt")
print("Backup complete")

Output

text
Backup complete

Example 2: Rename Many Files

Rename files using a loop.

python
import os

files = ["a.txt", "b.txt", "c.txt"]

count = 1

for file in files:
    new_name = f"file_{count}.txt"
    print(file, "->", new_name)
    count += 1

Output

text
a.txt -> file_1.txt
b.txt -> file_2.txt
c.txt -> file_3.txt

(Use os.rename() in a real folder.)

Example 3: Move Text Files

Move all .txt files into a folder.

python
import os
import shutil

files = ["notes.txt", "photo.jpg", "tasks.txt"]

for file in files:
    if file.endswith(".txt"):
        print("Move:", file)

Output

text
Move: notes.txt
Move: tasks.txt

(Use shutil.move() in a real folder.)

Example 4: Read Many Files

python
files = ["day1.txt", "day2.txt"]

for file in files:
    print("Reading", file)

Output

text
Reading day1.txt
Reading day2.txt

Build an Automation Mindset

Ask:

  • What task repeats often?
  • Can Python do it?
  • Can a loop handle many items?
  • Can files be organized automatically?

Code Along

Build a report creator.

python
with open("report.txt", "w") as file:
    file.write("Daily Report Ready")

print("Report created")

Output

text
Report created

Mini Challenge

Build a file organizer.

Steps:

  • Create a list:
python
["notes.txt", "photo.jpg", "tasks.txt", "music.mp3"]
  • Use a loop
  • Print only files ending with .txt
  • Print message:
text
Move notes.txt
Move tasks.txt

Expected output:

text
Move notes.txt
Move tasks.txt

Real World Use Case

Companies use automation for backups, reports, email lists, file cleanup, data exports, and scheduled tasks.

Quiz

  1. What is automation?
  2. Why is automation useful?
  3. Which Python tool helps repeat actions?
  4. Which module can move files?

Assignment

Create a script that prints all .csv files from a list of file names.

Summary

You learned how Python can automate repeated tasks using loops, conditions, files, os, and shutil.