Best Python Scripts for Automating Everyday Developer Tasks

If you’re a developer spending hours on repetitive tasks like file cleanup, API testing, or code formatting, Python scripts can automate them in minutes. From renaming hundreds of files to deploying code to servers with one command, these practical scripts save time and reduce errors. In this guide, you’ll find ready-to-use Python scripts for file management, Git workflows, testing, deployment, and system monitoring—each with real code snippets and actionable tips.

Developer writing Python automation script on laptop with terminal open

Photo by Jakub Zerdzicki on Pexels

## Why Automate with Python?

Python is the go-to language for automation because it’s readable, cross-platform, and has a huge library ecosystem. With just a few lines, you can replace hours of manual work. Below are the best scripts for everyday tasks, organized by use case.

## 1. File and Folder Management

### Bulk File Renamer

Rename hundreds of files in seconds with pattern matching.

“`python

import os

def rename_files(directory, prefix):

for i, filename in enumerate(os.listdir(directory)):

src = os.path.join(directory, filename)

dst = os.path.join(directory, f”{prefix}_{i}.txt”)

os.rename(src, dst)

rename_files(“./downloads”, “report”)

“`

Tip: Add error handling for existing files to avoid overwrites.

### Clean Up Old Logs

Delete files older than 30 days automatically.

“`python

import os, time

def clean_old_files(path, days=30):

now = time.time()

for f in os.listdir(path):

filepath = os.path.join(path, f)

if os.path.isfile(filepath) and now – os.path.getmtime(filepath) > days * 86400:

os.remove(filepath)

clean_old_files(“/var/logs/”)

“`

Actionable tip: Run this as a cron job weekly.

## 2. Git Automation Scripts

### Auto-Commit and Push

Commit all changes with a timestamp and push to remote.

“`python

import subprocess

def auto_commit():

subprocess.run([“git”, “add”, “.”])

subprocess.run([“git”, “commit”, “-m”, f”Auto-commit {datetime.now()}”])

subprocess.run([“git”, “push”])

auto_commit()

“`

Warning: Only use on personal branches—never on main without review.

### Batch Branch Cleanup

Delete local branches that are already merged.

“`python

import subprocess

def clean_branches():

branches = subprocess.check_output([“git”, “branch”, “–merged”]).decode().split()

for branch in branches:

if branch != “main” and branch != “master”:

subprocess.run([“git”, “branch”, “-d”, branch])

clean_branches()

“`

Git branch diagram showing merged branches being deleted by script

Photo by Daniil Komov on Pexels

## 3. Testing and Quality Assurance

### Automated API Tester

Test endpoints with retry logic and report failures.

“`python

import requests, time

def test_api(url, expected_status=200, retries=3):

for i in range(retries):

try:

resp = requests.get(url, timeout=5)

if resp.status_code == expected_status:

print(f”PASS: {url}”)

return True

except:

time.sleep(2)

print(f”FAIL: {url} after {retries} retries”)

return False

test_api(“https://api.example.com/health”)

“`

Pro tip: Integrate with CI/CD pipelines for automatic checks.

### Code Linter Runner

Check all Python files in a project for style issues.

“`python

import subprocess, glob

def lint_project():

files = glob.glob(“**/*.py”, recursive=True)

for f in files:

result = subprocess.run([“pylint”, f], capture_output=True, text=True)

if “error” in result.stdout.lower():

print(f”Issue in {f}”)

lint_project()

“`

## 4. Deployment and DevOps Scripts

### Docker Container Restarter

Restart containers if they become unhealthy.

“`python

import subprocess, time

def restart_unhealthy_containers():

output = subprocess.check_output([“docker”, “ps”, “–filter”, “health=unhealthy”, “-q”]).decode().strip()

if output:

subprocess.run([“docker”, “restart”] + output.split())

print(f”Restarted containers: {output}”)

while True:

restart_unhealthy_containers()

time.sleep(60)

“`

### Environment Setup Script

Automatically install dependencies and set up a dev environment.

“`python

import subprocess

def setup_env():

subprocess.run([“python3”, “-m”, “venv”, “venv”])

subprocess.run([“source”, “venv/bin/activate”, “&&”, “pip”, “install”, “-r”, “requirements.txt”], shell=True)

subprocess.run([“cp”, “.env.example”, “.env”])

print(“Environment ready!”)

setup_env()

“`

## 5. System Monitoring and Alerts

### Disk Space Monitor

Send email alert when disk usage exceeds 90%.

“`python

import shutil, smtplib

def check_disk():

usage = shutil.disk_usage(“/”)

percent = usage.used / usage.total * 100

if percent > 90:

server = smtplib.SMTP(“smtp.example.com”)

server.sendmail(“[email protected]”, “[email protected]”, f”Disk usage at {percent:.1f}%”)

print(“Alert sent!”)

check_disk()

“`

### CPU and Memory Logger

Log resource usage every hour for analysis.

“`python

import psutil, time, csv

def log_usage(file=”usage.csv”):

with open(file, “a”) as f:

writer = csv.writer(f)

writer.writerow([time.time(), psutil.cpu_percent(), psutil.virtual_memory().percent])

while True:

log_usage()

time.sleep(3600)

“`

System monitoring dashboard showing CPU and memory usage graphs

Photo by Tima Miroshnichenko on Pexels

## Comparison: Which Scripts to Use First?

Task Script Time Saved (Weekly) Difficulty
Bulk file rename File renamer 30 min Easy
Git cleanup Branch cleanup 20 min Easy
API testing API tester 1 hour Medium
Docker health Container restarter 2 hours Medium
Disk monitoring Disk monitor 15 min Easy

Start with the Easy ones for quick wins, then move to Medium scripts for bigger time savings.

## How to Run These Scripts

1. Save each script as a `.py` file (e.g., `clean_logs.py`).

2. Install dependencies with `pip install requests psutil`.

3. Run from terminal: `python3 script_name.py`.

4. Schedule with cron (Linux) or Task Scheduler (Windows) for automation.

Pro tip: Use `argparse` to add command-line arguments for flexibility.

## Common Pitfalls to Avoid

  • Hardcoding paths – use environment variables or config files.
  • Missing error handling – wrap critical sections in try/except.
  • Running as root – use least privilege principle.
  • No logging – add `logging` module to track script activity.

## Conclusion

Python scripts can automate the most tedious parts of your developer workflow—from file management to deployment and monitoring. Start with the file renamer or API tester today, and you’ll save hours each week. For more ready-to-use scripts and tools, visit freefile.store and download our curated collection of developer automation resources.

Ready to supercharge your workflow? Download Python automation scripts at freefile.store – your source for free developer tools and DevOps resources.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *