7 Surprisingly Helpful Python Scripts You’ll Use Each Week

7 Surprisingly Helpful Python Scripts You’ll Use Each Week7 Surprisingly Helpful Python Scripts You’ll Use Each Week
Picture by Creator | Ideogram

 

Introduction

 
Python isn’t only for information science, constructing apps, or making video games. I used to be educating my youthful brother, Qasim, Python, and I noticed he linked much more once I confirmed him sensible scripts that might automate boring, repetitive duties we regularly cope with each week. One factor I’ve noticed in life is {that a} bunch of small, unproductive, time-consuming duties can critically drain your power. You find yourself with little motivation or focus for the issues that really matter. So, I’m right here that will help you out with among the most typical duties that you simply encounter nearly each week and the way they are often automated with Python simply, saving you tons of time and power.

I’ve saved the scripts clear and easy, however you possibly can add complexity to them as per your necessities. So, let’s get began.

 

1. Automated File Organizer by Extension

 
To be sincere, generally once I’m working, my Downloads folder turns into an absolute mess. I’ll share a easy Python script that can loop by means of the information in your goal listing and organize them (e.g., photographs, paperwork, movies) by extension utilizing os and shutil. Let’s take a look:

import os
import shutil
from pathlib import Path

# Folder to arrange (e.g., Downloads)
base_folder = Path.house() / "Downloads"

# Outline folders for every extension
folders = {
    "photographs": ["jpg", "png", "gif", "bmp"],
    "paperwork": ["txt", "pdf", "docx"],
    "archives": ["zip", "rar", "tar", "gz"],
    "audio": ["mp3", "wav"],
    # add extra classes as wanted
}

# Iterate over information in base_folder
for merchandise in base_folder.iterdir():
    if merchandise.is_file():
        ext = merchandise.suffix.decrease().lstrip('.')
        moved = False
        # Decide which class folder to make use of
        for folder, ext_list in folders.objects():
            if ext in ext_list:
                dest_dir = base_folder / folder
                dest_dir.mkdir(exist_ok=True)
                merchandise.rename(dest_dir / merchandise.title)
                moved = True
                break
        # If extension didn’t match any class, transfer to "others"
        if not moved:
            dest_dir = base_folder / "others"
            dest_dir.mkdir(exist_ok=True)
            merchandise.rename(dest_dir / merchandise.title)

 

2. System Useful resource Monitor with Alerts

 
If you happen to’re somebody like me who runs a number of tabs, apps, and scripts collectively, it’s simple to lose observe of your system efficiency. This script, utilizing the psutil library, helps you monitor your CPU and RAM utilization. You may even set alerts if utilization crosses a sure threshold.

import psutil
import time

CPU_LIMIT = 80  # in share
MEMORY_LIMIT = 80  # in share

whereas True:
    cpu = psutil.cpu_percent(interval=1)
    reminiscence = psutil.virtual_memory().%

    print(f"CPU: {cpu}%, Reminiscence: {reminiscence}%")

    if cpu > CPU_LIMIT:
        print("⚠️ CPU utilization is excessive!")

    if reminiscence > MEMORY_LIMIT:
        print("⚠️ Reminiscence utilization is excessive!")

    time.sleep(5)

 

Run it for some time, and also you’ll begin noticing how issues spike whenever you’re modifying movies or working a heavy script.

 

3. Automated E mail Reporter

 
E mail eats up far more time than we predict. Whether or not it’s replying to updates, sending out reminders, following up, or simply maintaining folks within the loop, we regularly spend hours each week doing issues that may (and will) be automated. And if you happen to’re something like me, you in all probability overthink what to jot down in these common replace emails, find yourself procrastinating, after which rush by means of it later. This straightforward script may be actually helpful, and right here’s how one can set it up:

import smtplib
from electronic mail.mime.textual content import MIMEText

sender = "[email protected]"
receiver = "[email protected]"
topic = "Each day Report"
physique = "That is your automated electronic mail for at present."

msg = MIMEText(physique)
msg["Subject"] = topic
msg["From"] = sender
msg["To"] = receiver

# For safety, use atmosphere variables or getpass as a substitute of hardcoding.
password = "your_password" 

with smtplib.SMTP_SSL("smtp.gmail.com", 465) as server:
    server.login("[email protected]", password)
    server.send_message(msg)

print("E mail despatched!")

 

⚠️ Heads up: If you happen to’re utilizing Gmail, ensure you’ve enabled much less safe app entry or arrange an app-specific password when you have 2FA enabled.

 

4. Desktop Notifications

 
I truly began utilizing this script to assist me keep on with the Pomodoro Method (25 minutes of deep focus adopted by a 5-minute break). And truthfully, it labored wonders for my focus and power ranges all through the day. It’s nice if you need one thing that pops up a bit reminder in your display with out switching apps or setting alarms. You should use it for something like stretch reminders, hydration alerts, and even to remind your self to cease doomscrolling.
Since I’m on macOS, I’m utilizing the built-in osascript command to set off native system notifications. However if you happen to’re on Home windows or Linux, you need to use the plyer library for related performance.

Here is how I set it up for my very own workflow:

import time
import os

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

# Pomodoro session settings
work_duration = 25 * 60  # 25 minutes
break_duration = 5 * 60  # 5 minutes
cycles = 4  # Variety of Pomodoro periods

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

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

# Last notification
notify("All Completed!", "You’ve accomplished all of your Pomodoros 🎉")

 

5. Password Generator and Supervisor

 
If you happen to’re nonetheless utilizing the identical password all over the place (please don’t), that is for you. It generates a safe password and shops it safely (you possibly can later encrypt the storage half too).

import random
import string

def generate_password(size=12):
    chars = string.ascii_letters + string.digits + string.punctuation
    password = "".be a part of(random.selection(chars) for _ in vary(size))
    return password

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

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

 

For extra safety, look into encrypting the file with cryptography or storing it in a safe vault like keyring.

 

6. Seek for Textual content in A number of Recordsdata

 
After I’m engaged on writing materials, I normally have tons of uncooked concepts scattered throughout numerous information in numerous folders. Typically I bear in mind writing an excellent analogy or a code snippet weeks in the past… however I don’t know the place I saved it. This little script has saved me numerous hours. As a substitute of manually opening each file to seek for a phrase like “machine studying” or “vector search,” I simply run this Python script and let it scan every thing for me.

import os

search_dir = "your_directory"  # Change with the trail to your notes
search_term = "machine studying"

for root, dirs, information in os.stroll(search_dir):
    for file in information:
        if file.endswith(".txt") or file.endswith(".md"):
            file_path = os.path.be a part of(root, file)
            attempt:
                with open(file_path, "r", encoding="utf-8") as f:
                    content material = f.learn()
                    if search_term.decrease() in content material.decrease():
                        print(f"✅ Present in: {file_path}")
            besides Exception as e:
                print(f"❌ Skipped {file_path} (error studying file)")

 
It is a easy model that works nice for plain textual content information. Since I additionally work with .docx, .pptx, and .pdf information, I exploit a barely extra superior model that helps these codecs too. You may simply lengthen this script utilizing libraries like python-docx, python-pptx, and pdfplumber to make it a mini search engine in your complete workspace.

 

7. Discovering Internships and Scholarships on Twitter

 
Twitter/X could be a goldmine if you know the way to make use of it well. After I was actively trying to find grasp’s and PhD scholarships, I noticed that you simply don’t simply should be certified, however you additionally should be fast and conscious. Many nice alternatives pop up on Twitter (sure, critically), however they vanish quick if you happen to’re not watching carefully. There are two nice methods to do that in Python: utilizing both the snscrape library or Twitter’s official API. In order for you extra management (like filtering by language, excluding retweets, and many others.), you need to use Twitter’s official API v2. Even with the free model, you get restricted entry to current tweets. For this script, we are going to use the requests library to work together with the API and pandas to arrange the outcomes.

You’ll want 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'  # Change this together with your token

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

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

# Key phrases that normally present up in tutorial alternatives
question = (
    '(phd OR "phd place" OR "grasp place" OR "absolutely funded") '
    '("apply now" OR "open place" OR "graduate place") '
    '-is:retweet lang:en'
)

params = {
    'question': question,
    'max_results': 10,  # Max is 100 for current search
    'tweet.fields': 'author_id,created_at,textual content',
    'expansions': 'author_id',
    'person.fields': 'username,title',
}

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

def extract_tweet_info(information):
    customers = {u['id']: u for u in information.get('contains', {}).get('customers', [])}
    tweets_info = []

    for tweet in information.get('information', []):
        person = customers.get(tweet['author_id'], {})
        tweet_url = f"https://twitter.com/{person.get('username')}/standing/{tweet['id']}"

        tweets_info.append({
            'Date': tweet['created_at'],
            'Username': person.get('username'),
            'Identify': person.get('title'),
            'Textual content': tweet['text'],
            'Tweet_URL': tweet_url
        })

    return pd.DataFrame(tweets_info)

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

 

You may run this weekly and save the outcomes to a CSV and even electronic mail them to your self.

 

Wrapping Up

 
Actually, I didn’t begin utilizing Python for automation, however over time I noticed how a lot time goes into small, repetitive stuff that quietly eats away at my focus. These scripts may appear fundamental, however they genuinely assist release time and headspace.

You don’t have to automate every thing. Simply decide the one or two duties that you simply do probably the most usually and construct from there. I’ve discovered that when you begin with easy automation, you start recognizing extra methods to make life a bit simpler. That’s the place it actually begins to click on.

Let me know if you find yourself utilizing any of those or construct your individual variations. I might like to see what you give you.
 
 

Kanwal Mehreen is a machine studying engineer and a technical author with a profound ardour for information science and the intersection of AI with drugs. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Technology Scholar 2022 for APAC, she champions range and tutorial excellence. She’s additionally acknowledged as a Teradata Variety in Tech Scholar, Mitacs Globalink Analysis Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having based FEMCodes to empower ladies in STEM fields.