If you spend time doing the same tasks on your computer every day, Python scripts for automation can save you hours every week. You do not need to be an expert programmer to start. These scripts are practical, beginner-friendly, and ready to copy and use right away.
Python is one of the most popular languages for automation because it is simple to read and has a massive library ecosystem. Whether you want to organize files, send emails, or scrape data from websites, there is a Python script for that.
This article covers 20 real-world automation scripts. Each one solves a common problem that almost everyone faces.
Why Use Python for Automation?
Automation means making your computer do repetitive tasks for you. Instead of clicking through folders or copying data manually, you write a script once and let Python handle the rest.
Here are some key reasons why Python is ideal for this:
- It has a clean, readable syntax that beginners can learn quickly.
- It works on Windows, Mac, and Linux.
- It has thousands of free libraries for every kind of task.
- The community is massive, so finding help is easy.
If you are new to the language, check out this complete guide to getting started with Python before diving into the scripts.
Scripts for File and Folder Management
Keeping your computer organized takes time. These scripts do it automatically.
1. Auto-Organize Downloads Folder
This script scans your Downloads folder and moves files into subfolders based on file type (images, PDFs, videos, etc.).
import os
import shutil
source = os.path.expanduser("~/Downloads")
categories = {
"Images": [".jpg", ".jpeg", ".png", ".gif"],
"PDFs": [".pdf"],
"Videos": [".mp4", ".mov", ".avi"],
"Archives": [".zip", ".tar", ".gz"],
}
for filename in os.listdir(source):
ext = os.path.splitext(filename)[1].lower()
for folder, extensions in categories.items():
if ext in extensions:
dest = os.path.join(source, folder)
os.makedirs(dest, exist_ok=True)
shutil.move(os.path.join(source, filename), dest)You can learn more about file handling techniques in this article on moving and copying files with shutil.
2. Bulk File Renamer
Rename hundreds of files in seconds using a pattern you define.
import os
folder = "/path/to/your/folder"
prefix = "project_"
for i, filename in enumerate(os.listdir(folder)):
ext = os.path.splitext(filename)[1]
new_name = f"{prefix}{i+1:03d}{ext}"
os.rename(
os.path.join(folder, filename),
os.path.join(folder, new_name)
)3. Automatic Backup Script
This script copies important folders to a backup location and compresses them into a ZIP file.
import shutil
import os
from datetime import datetime
source = "/path/to/important/folder"
backup_dir = "/path/to/backup"
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = os.path.join(backup_dir, f"backup_{timestamp}")
shutil.copytree(source, backup_path)
shutil.make_archive(backup_path, "zip", backup_path)
shutil.rmtree(backup_path)
print("Backup complete!")
For more on this topic, see how to create automatic backups with Python.
4. Find and Delete Duplicate Files
Scan a folder and remove files that appear more than once.
import os
import hashlib
def hash_file(path):
h = hashlib.md5()
with open(path, "rb") as f:
h.update(f.read())
return h.hexdigest()
folder = "/path/to/folder"
seen = {}
for fname in os.listdir(folder):
fpath = os.path.join(folder, fname)
fhash = hash_file(fpath)
if fhash in seen:
os.remove(fpath)
print(f"Deleted duplicate: {fname}")
else:
seen[fhash] = fpath
5. Monitor a Folder for New Files
Get notified whenever a new file appears in a specific folder using the watchdog library.
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time
class Handler(FileSystemEventHandler):
def on_created(self, event):
print(f"New file detected: {event.src_path}")
observer = Observer()
observer.schedule(Handler(), path="/path/to/watch", recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
This is also covered in detail in the guide on monitoring folders in real time with watchdog.
Scripts for Web and Data Automation
These scripts pull data from the web and process it automatically.
6. Web Scraper for News Headlines
Collect news headlines from a website and save them to a text file.
import requests
from bs4 import BeautifulSoup
url = "https://news.ycombinator.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
titles = soup.select(".titleline > a")
with open("headlines.txt", "w") as f:
for title in titles:
f.write(title.text + "\n")
print("Headlines saved!")
7. Price Tracker and Alert Bot
Check a product price online and send an alert when it drops below a threshold.
import requests
from bs4 import BeautifulSoup
url = "https://example.com/product-page"
target_price = 50.00
headers = {"User-Agent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, "html.parser")
price_text = soup.select_one(".price").text
price = float(price_text.replace("$", "").strip())
if price < target_price:
print(f"Price dropped to ${price}! Time to buy.")
else:
print(f"Current price: ${price}. Not yet.")
You can expand this idea into a full bot that alerts you when a product drops in price.
8. Download All Images from a Webpage
Automatically download every image found on a specific URL.
import requests
from bs4 import BeautifulSoup
import os
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
os.makedirs("images", exist_ok=True)
for img in soup.find_all("img"):
src = img.get("src")
if src and src.startswith("http"):
img_data = requests.get(src).content
filename = src.split("/")[-1]
with open(f"images/{filename}", "wb") as f:
f.write(img_data)
9. CSV Data Cleaner
Remove empty rows, fix column names, and strip extra whitespace from messy CSV files.
import pandas as pd
df = pd.read_csv("messy_data.csv")
df.columns = df.columns.str.strip().str.lower().str.replace(" ", "_")
df.dropna(how="all", inplace=True)
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
df.to_csv("clean_data.csv", index=False)
print("Data cleaned and saved!")
For a deeper look at data handling, explore how to clean dirty data with Python.
10. API Data Fetcher and Saver
Pull data from any public API and save the results to a JSON file automatically.
import requests
import json
url = "https://api.coindesk.com/v1/bpi/currentprice.json"
response = requests.get(url)
data = response.json()
with open("bitcoin_price.json", "w") as f:
json.dump(data, f, indent=4)
print("Data saved to bitcoin_price.json")
Scripts for Communication Automation
Save time on emails and messages with these ready-to-use scripts.
11. Automated Email Sender
Send personalized emails to a list of recipients using Python’s built-in smtplib.
import smtplib
from email.mime.text import MIMEText
sender = "[email protected]"
password = "your_password"
recipients = ["[email protected]", "[email protected]"]
for recipient in recipients:
msg = MIMEText(f"Hello! This is an automated message for {recipient}.")
msg["Subject"] = "Automated Email"
msg["From"] = sender
msg["To"] = recipient
with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
server.login(sender, password)
server.send_message(msg)
print(f"Email sent to {recipient}")
Check the full tutorial on automating emails with Python.
12. Telegram Notification Bot
Send yourself a message on Telegram whenever something important happens in your script.
import requests
TOKEN = "your_bot_token"
CHAT_ID = "your_chat_id"
message = "Your script finished running!"
url = f"https://api.telegram.org/bot{TOKEN}/sendMessage"
requests.post(url, data={"chat_id": CHAT_ID, "text": message})
Scripts for System and Task Automation
These scripts take over system-level tasks so you do not have to do them manually.
13. Schedule a Task to Run Daily
Use Python’s schedule library to run any function at a specific time every day.
import schedule
import time
def daily_task():
print("Running daily task...")
schedule.every().day.at("08:00").do(daily_task)
while True:
schedule.run_pending()
time.sleep(60)
14. System Resource Monitor
Log CPU and memory usage every minute to a file for performance tracking.
import psutil
import time
from datetime import datetime
while True:
cpu = psutil.cpu_percent()
mem = psutil.virtual_memory().percent
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("system_log.txt", "a") as f:
f.write(f"{timestamp} | CPU: {cpu}% | RAM: {mem}%\n")
time.sleep(60)
15. Compress Files Older Than 30 Days
Automatically archive old files to free up disk space.
import os
import shutil
import time
folder = "/path/to/folder"
archive = "/path/to/archive"
os.makedirs(archive, exist_ok=True)
now = time.time()
cutoff = 30 * 86400
for fname in os.listdir(folder):
fpath = os.path.join(folder, fname)
if os.path.getmtime(fpath) < now - cutoff:
shutil.move(fpath, archive)
print(f"Archived: {fname}")
You can also learn how to compress files into ZIP archives with Python.
Scripts for Text and Document Processing
These scripts process documents so you do not have to open them manually.
16. Extract Text from PDF Files
Pull all the text out of a PDF and save it as a plain text file.
import PyPDF2
with open("document.pdf", "rb") as f:
reader = PyPDF2.PdfReader(f)
text = ""
for page in reader.pages:
text += page.extract_text()
with open("output.txt", "w") as out:
out.write(text)
print("Text extracted successfully!")
See also the full guide on extracting text from PDFs with Python.
17. Word Frequency Counter
Count how many times each word appears in a text file.
from collections import Counter
import re
with open("text.txt", "r") as f:
text = f.read().lower()
words = re.findall(r'\b[a-z]+\b', text)
counter = Counter(words)
for word, count in counter.most_common(10):
print(f"{word}: {count}")
18. Auto-Generate a Report from CSV Data
Read a CSV file and produce a formatted text report with key statistics.
import pandas as pd
df = pd.read_csv("sales.csv")
report = f"""
Sales Report
============
Total Sales: {df['sales'].sum()}
Average: {df['sales'].mean():.2f}
Top Region: {df.groupby('region')['sales'].sum().idxmax()}
"""
with open("report.txt", "w") as f:
f.write(report)
print("Report generated!")
19. Translate a Text File Automatically
Use the deep-translator library to translate any text file into another language.
from deep_translator import GoogleTranslator
with open("original.txt", "r") as f:
text = f.read()
translated = GoogleTranslator(source="auto", target="es").translate(text)
with open("translated.txt", "w") as f:
f.write(translated)
print("Translation complete!")
20. QR Code Generator for Any URL
Generate a QR code image from any link or text in just a few lines.
import qrcode
data = "https://academify.com.br"
img = qrcode.make(data)
img.save("qrcode.png")
print("QR code saved as qrcode.png")
For a full tutorial on this, check the guide on generating QR codes with Python.
How to Run These Scripts
If you are new to Python, running scripts is easier than you think. Here is a quick overview:
- Make sure Python is installed on your computer.
- Open a terminal or command prompt.
- Install any required library with
pip install library-name. - Save the script as a
.pyfile. - Run it with
python script_name.py.
Tip: If you need to install libraries without an internet connection, learn how to install Python packages offline.
For more complex setups, the Python documentation on the subprocess module is an excellent official reference.
Frequently Asked Questions (FAQ)
1. What is a Python automation script? It is a Python file that performs repetitive tasks automatically, without you needing to do them manually each time.
2. Do I need to be an expert to use these scripts? No. Most scripts here are beginner-friendly. Basic Python knowledge is enough to get started.
3. Are these scripts safe to use? Yes, as long as you understand what each script does before running it. Always test on non-critical files first.
4. Can I run these scripts on Windows? Yes. All scripts in this article work on Windows, Mac, and Linux with Python installed.
5. How do I install missing libraries? Open the terminal and type pip install library-name. Replace “library-name” with the actual package.
6. Can I schedule these scripts to run automatically? Yes. Use the schedule library (script #13) or the system’s task scheduler (Task Scheduler on Windows, cron on Mac/Linux).
7. What is the best editor to write Python scripts? VS Code is a popular choice. You can see a full setup guide at how to install and configure VS Code.
8. Can I combine multiple scripts into one? Yes. You can import functions from other scripts and call them together in a single main file.
9. How do I avoid errors when a file is not found? Use try/except blocks to handle errors gracefully. Learn how in this guide to try/except in Python.
10. Is Python the best language for automation? Python is one of the best due to its simplicity and library support. It is widely used for automation across industries.
11. Can I automate browser actions with Python? Yes. Libraries like Selenium let you control a browser automatically. Check out the Selenium guide for more.
12. Where can I find more Python automation scripts? Right here on Academify. Browse articles on topics like web scraping, bots, file handling, and more.

