Home » 7 Surprisingly Useful Python Scripts You’ll Use Every Week

7 Surprisingly Useful Python Scripts You’ll Use Every Week

7 Surprisingly Useful Python Scripts You’ll Use Every Week
Image by Author | Ideogram

 

Introduction

 
Python isn’t just for data science, building apps, or making games. I was teaching my younger brother, Qasim, Python, and I realized he connected a lot more when I showed him practical scripts that could automate boring, repetitive tasks we often deal with every week. One thing I’ve observed in life is that a bunch of small, unproductive, time-consuming tasks can seriously drain your energy. You end up with little motivation or focus for the things that actually matter. So, I’m here to help you out with some of the most common tasks that you encounter almost every week and how they can be automated with Python easily, saving you tons of time and energy.

I’ve kept the scripts clean and simple, but you can add complexity to them as per your requirements. So, let’s get started.

 

1. Automated File Organizer by Extension

 
To be honest, sometimes when I’m working, my Downloads folder becomes an absolute mess. I’ll share a simple Python script that will loop through the files in your target directory and arrange them (e.g., images, documents, videos) by extension using os and shutil. Let’s have a look:

import os
import shutil
from pathlib import Path

# Folder to organize (e.g., Downloads)
base_folder = Path.home() / "Downloads"

# Define folders for each extension
folders = {
    "images": ["jpg", "png", "gif", "bmp"],
    "documents": ["txt", "pdf", "docx"],
    "archives": ["zip", "rar", "tar", "gz"],
    "audio": ["mp3", "wav"],
    # add more categories as needed
}

# Iterate over files in base_folder
for item in base_folder.iterdir():
    if item.is_file():
        ext = item.suffix.lower().lstrip('.')
        moved = False
        # Determine which category folder to use
        for folder, ext_list in folders.items():
            if ext in ext_list:
                dest_dir = base_folder / folder
                dest_dir.mkdir(exist_ok=True)
                item.rename(dest_dir / item.name)
                moved = True
                break
        # If extension didn’t match any category, move to "others"
        if not moved:
            dest_dir = base_folder / "others"
            dest_dir.mkdir(exist_ok=True)
            item.rename(dest_dir / item.name)

 

2. System Resource Monitor with Alerts

 
If you’re someone like me who runs multiple tabs, apps, and scripts together, it’s easy to lose track of your system performance. This script, using the psutil library, helps you monitor your CPU and RAM usage. You can even set alerts if usage crosses a certain threshold.

import psutil
import time

CPU_LIMIT = 80  # in percentage
MEMORY_LIMIT = 80  # in percentage

while True:
    cpu = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory().percent

    print(f"CPU: {cpu}%, Memory: {memory}%")

    if cpu > CPU_LIMIT:
        print("⚠️ CPU usage is high!")

    if memory > MEMORY_LIMIT:
        print("⚠️ Memory usage is high!")

    time.sleep(5)

 

Run it for a while, and you’ll start noticing how things spike when you’re editing videos or running a heavy script.

 

3. Automated Email Reporter

 
Email eats up way more time than we think. Whether it’s replying to updates, sending out reminders, following up, or just keeping people in the loop, we often spend hours every week doing things that can (and should) be automated. And if you’re anything like me, you probably overthink what to write in those regular update emails, end up procrastinating, and then rush through it later. This simple script can be really useful, and here’s how you can set it up:

import smtplib
from email.mime.text import MIMEText

sender = "youremail@example.com"
receiver = "receiver@example.com"
subject = "Daily Report"
body = "This is your automated email for today."

msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = receiver

# For security, use environment variables or getpass instead of hardcoding.
password = "your_password" 

with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login("youremail@example.com", password)
    server.send_message(msg)

print("Email sent!")

 

⚠️ Heads up: If you’re using Gmail, make sure you’ve enabled less secure app access or set up an app-specific password if you have 2FA enabled.

 

4. Desktop Notifications

 
I actually started using this script to help me stick to the Pomodoro Technique (25 minutes of deep focus followed by a 5-minute break). And honestly, it worked wonders for my concentration and energy levels throughout the day. It’s great if you want something that pops up a little reminder on your screen without switching apps or setting alarms. You can use it for anything like stretch reminders, hydration alerts, or even to remind yourself to stop doomscrolling.
Since I’m on macOS, I’m using the built-in osascript command to trigger native system notifications. But if you’re on Windows or Linux, you can use the plyer library for similar functionality.

Here’s how I set it up for my own workflow:

import time
import os

def notify(title, message):
    os.system(f'''
        osascript -e 'display notification "{message}" with title "{title}"'
    ''')

# Pomodoro session settings
work_duration = 25 * 60  # 25 minutes
break_duration = 5 * 60  # 5 minutes
cycles = 4  # Number of Pomodoro sessions

for i in range(cycles):
    # Work phase
    notify(f"Pomodoro {i + 1} - Focus Time", "Time to focus! Work for 25 minutes.")
    time.sleep(work_duration)

    # Break phase
    notify("Break Time", "Nice work! Take a 5-minute break.")
    time.sleep(break_duration)

# Final notification
notify("All Done!", "You’ve completed all your Pomodoros 🎉")

 

5. Password Generator and Manager

 
If you’re still using the same password everywhere (please don’t), this is for you. It generates a secure password and stores it safely (you can later encrypt the storage part too).

import random
import string

def generate_password(length=12):
    chars = string.ascii_letters + string.digits + string.punctuation
    password = "".join(random.choice(chars) for _ in range(length))
    return password

new_password = generate_password()
print("Generated Password:", new_password)

# Save to file (simple way)
with open("passwords.txt", "a") as file:
    file.write(f"MySite: {new_password}n")

 

For more security, look into encrypting the file with cryptography or storing it in a secure vault like keyring.

 

6. Search for Text in Multiple Files

 
When I’m working on writing material, I usually have tons of raw ideas scattered across various files in different folders. Sometimes I remember writing a brilliant analogy or a code snippet weeks ago… but I have no idea where I saved it. This little script has saved me countless hours. Instead of manually opening every file to search for a phrase like “machine learning” or “vector search,” I just run this Python script and let it scan everything for me.

import os

search_dir = "your_directory"  # Replace with the path to your notes
search_term = "machine learning"

for root, dirs, files in os.walk(search_dir):
    for file in files:
        if file.endswith(".txt") or file.endswith(".md"):
            file_path = os.path.join(root, file)
            try:
                with open(file_path, "r", encoding="utf-8") as f:
                    content = f.read()
                    if search_term.lower() in content.lower():
                        print(f"✅ Found in: {file_path}")
            except Exception as e:
                print(f"❌ Skipped {file_path} (error reading file)")

 
This is a simple version that works great for plain text files. Since I also work with .docx, .pptx, and .pdf files, I use a slightly more advanced version that supports those formats too. You can easily extend this script using libraries like python-docx, python-pptx, and pdfplumber to make it a mini search engine for your entire workspace.

 

7. Finding Internships and Scholarships on Twitter

 
Twitter/X can be a goldmine if you know how to use it smartly. When I was actively searching for master’s and PhD scholarships, I realized that you don’t just need to be qualified, but you also need to be quick and aware. Many great opportunities pop up on Twitter (yes, seriously), but they vanish fast if you’re not watching closely. There are two great ways to do this in Python: using either the snscrape library or Twitter’s official API. If you want more control (like filtering by language, excluding retweets, etc.), you can use Twitter’s official API v2. Even with the free version, you get limited access to recent tweets. For this script, we will use the requests library to interact with the API and pandas to organize the results.

You’ll need a developer account and a Bearer Token (from the Twitter/X Developer Portal).

import requests
import pandas as pd

BEARER_TOKEN = 'YOUR_TWITTER_BEARER_TOKEN'  # Replace this with your token

headers = {
    "Authorization": f"Bearer {BEARER_TOKEN}"
}

search_url = "https://api.twitter.com/2/tweets/search/recent"

# Keywords that usually show up in academic opportunities
query = (
    '(phd OR "phd position" OR "master position" OR "fully funded") '
    '("apply now" OR "open position" OR "graduate position") '
    '-is:retweet lang:en'
)

params = {
    'query': query,
    'max_results': 10,  # Max is 100 for recent search
    'tweet.fields': 'author_id,created_at,text',
    'expansions': 'author_id',
    'user.fields': 'username,name',
}

def get_tweets():
    response = requests.get(search_url, headers=headers, params=params)
    if response.status_code != 200:
        raise Exception(f"Request failed: {response.status_code}, {response.text}")
    return response.json()

def extract_tweet_info(data):
    users = {u['id']: u for u in data.get('includes', {}).get('users', [])}
    tweets_info = []

    for tweet in data.get('data', []):
        user = users.get(tweet['author_id'], {})
        tweet_url = f"https://twitter.com/{user.get('username')}/status/{tweet['id']}"

        tweets_info.append({
            'Date': tweet['created_at'],
            'Username': user.get('username'),
            'Name': user.get('name'),
            'Text': tweet['text'],
            'Tweet_URL': tweet_url
        })

    return pd.DataFrame(tweets_info)

if __name__ == "__main__":
    data = get_tweets()
    df = extract_tweet_info(data)
    print(df[['Date', 'Username', 'Text', 'Tweet_URL']].head())
    df.to_csv('phd_masters_positions_twitter.csv', index=False)

 

You can run this weekly and save the results to a CSV or even email them to yourself.

 

Wrapping Up

 
Honestly, I didn’t start using Python for automation, but over time I realized how much time goes into small, repetitive stuff that quietly eats away at my focus. These scripts might seem basic, but they genuinely help free up time and headspace.

You don’t need to automate everything. Just pick the one or two tasks that you do the most often and build from there. I’ve found that once you start with simple automation, you begin spotting more ways to make life a bit easier. That’s where it really starts to click.

Let me know if you end up using any of these or build your own versions. I would love to see what you come up with.
 
 

Kanwal Mehreen is a machine learning engineer and a technical writer with a profound passion for data science and the intersection of AI with medicine. She co-authored the ebook “Maximizing Productivity with ChatGPT”. As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She’s also recognized as a Teradata Diversity in Tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having founded FEMCodes to empower women in STEM fields.

Related Posts

Leave a Reply

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