HomeArtificial Intelligence7 Surprisingly Helpful Python Scripts You’ll Use Each Week

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 knowledge science, constructing apps, or making video games. I used to be instructing my youthful brother, Qasim, Python, and I spotted he related much more after I confirmed him sensible scripts that might automate boring, repetitive duties we regularly take care of each week. One factor I’ve noticed in life is {that a} bunch of small, unproductive, time-consuming duties can severely drain your power. You find yourself with little motivation or focus for the issues that truly matter. So, I’m right here that can assist you out with a number of the commonest duties that you simply encounter virtually each week and the way they are often automated with Python simply, saving you tons of time and power.

I’ve stored 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 after I’m working, my Downloads folder turns into an absolute mess. I’ll share a easy Python script that can loop by the recordsdata in your goal listing and organize them (e.g., pictures, 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 = {
    "pictures": ["jpg", "png", "gif", "bmp"],
    "paperwork": ["txt", "pdf", "docx"],
    "archives": ["zip", "rar", "tar", "gz"],
    "audio": ["mp3", "wav"],
    # add extra classes as wanted
}

# Iterate over recordsdata 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.gadgets():
            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

 
In the event you’re somebody like me who runs a number of tabs, apps, and scripts collectively, it’s straightforward to lose observe of your system efficiency. This script, utilizing the psutil library, helps you monitor your CPU and RAM utilization. You’ll be able to 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 enhancing movies or working a heavy script.

 

3. Automated E-mail Reporter

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

import smtplib
from e-mail.mime.textual content import MIMEText

sender = "[email protected]"
receiver = "[email protected]"
topic = "Every day Report"
physique = "That is your automated e-mail for immediately."

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

# For safety, use atmosphere variables or getpass as an alternative 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: In the event you’re utilizing Gmail, be sure to’ve enabled much less safe app entry or arrange an app-specific password if in case you have 2FA enabled.

 

4. Desktop Notifications

 
I really began utilizing this script to assist me persist with the Pomodoro Method (25 minutes of deep focus adopted by a 5-minute break). And actually, 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 little bit reminder in your display screen 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 in case you’re on Home windows or Linux, you should 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 classes

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)

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

 

5. Password Generator and Supervisor

 
In the event you’re nonetheless utilizing the identical password in every single 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.alternative(chars) for _ in vary(size))
    return password

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

# Save to file (easy manner)
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

 
Once I’m engaged on writing materials, I often have tons of uncooked concepts scattered throughout varied recordsdata in several folders. Generally I bear in mind writing an excellent analogy or a code snippet weeks in the past… however I do not know the place I saved it. This little script has saved me numerous hours. As an alternative 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 all the pieces for me.

import os

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

for root, dirs, recordsdata in os.stroll(search_dir):
    for file in recordsdata:
        if file.endswith(".txt") or file.endswith(".md"):
            file_path = os.path.be a part of(root, file)
            strive:
                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 recordsdata. Since I additionally work with .docx, .pptx, and .pdf recordsdata, I exploit a barely extra superior model that helps these codecs too. You’ll be able to simply lengthen this script utilizing libraries like python-docx, python-pptx, and pdfplumber to make it a mini search engine on your total workspace.

 

7. Discovering Internships and Scholarships on Twitter

 
Twitter/X could be a goldmine if you understand how to make use of it well. Once I was actively trying to find grasp’s and PhD scholarships, I spotted that you simply don’t simply must be certified, however you additionally must be fast and conscious. Many nice alternatives pop up on Twitter (sure, severely), however they vanish quick in case you’re not watching intently. 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 so on.), you should use Twitter’s official API v2. Even with the free model, you get restricted entry to latest tweets. For this script, we’ll 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'  # Exchange this together with your token

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

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

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

params = {
    'question': question,
    'max_results': 10,  # Max is 100 for latest search
    'tweet.fields': 'author_id,created_at,textual content',
    'expansions': 'author_id',
    'consumer.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(knowledge):
    customers = {u['id']: u for u in knowledge.get('consists of', {}).get('customers', [])}
    tweets_info = []

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

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

    return pd.DataFrame(tweets_info)

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

 

You’ll be able to run this weekly and save the outcomes to a CSV and even e-mail them to your self.

 

Wrapping Up

 
Truthfully, I didn’t begin utilizing Python for automation, however over time I spotted 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 must automate all the pieces. Simply decide the one or two duties that you simply do probably the most usually and construct from there. I’ve discovered that after 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’d like to see what you give you.
 
 

Kanwal Mehreen is a machine studying engineer and a technical author with a profound ardour for knowledge science and the intersection of AI with drugs. She co-authored the e book “Maximizing Productiveness with ChatGPT”. As a Google Era Scholar 2022 for APAC, she champions variety 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 girls in STEM fields.



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments