0% found this document useful (0 votes)
25 views5 pages

Essential Python Automation Scripts

The document provides a list of top Python automation scripts designed to simplify everyday tasks, including web scraping, sending emails, bulk file renaming, and more. Each script is accompanied by code snippets and brief descriptions of their functionalities. Additionally, tips for usage and API requirements are included for certain scripts.

Uploaded by

mini10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views5 pages

Essential Python Automation Scripts

The document provides a list of top Python automation scripts designed to simplify everyday tasks, including web scraping, sending emails, bulk file renaming, and more. Each script is accompanied by code snippets and brief descriptions of their functionalities. Additionally, tips for usage and API requirements are included for certain scripts.

Uploaded by

mini10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Here are some top Python automation scripts that can simplify everyday tasks:

1. Automate Web Scraping (Extract Data from Websites)

This script fetches the latest news headlines from a website.

import requests

from bs4 import BeautifulSoup

url = "[Link]

response = [Link](url)

soup = BeautifulSoup([Link], "[Link]")

for idx, item in enumerate(soup.find_all("a", class_="storylink")[:5], start=1):

print(f"{idx}. {[Link]}")

2. Automate Sending Emails

Sends an email automatically.

import smtplib

from [Link] import EmailMessage

def send_email():

email = "your_email@[Link]"

password = "your_password"

recipient = "recipient_email@[Link]"

msg = EmailMessage()

msg["Subject"] = "Automated Email"

msg["From"] = email

msg["To"] = recipient

msg.set_content("Hello! This is an automated email.")

with smtplib.SMTP_SSL("[Link]", 465) as server:

[Link](email, password)

server.send_message(msg)
send_email()

print("Email sent successfully!")

🔹 Tip: Use an App Password instead of your Gmail password.

3. Bulk File Renaming

Renames all files in a folder sequentially.

import os

folder_path = "/path/to/folder"

prefix = "file_"

for count, filename in enumerate([Link](folder_path)):

old_path = [Link](folder_path, filename)

new_path = [Link](folder_path, f"{prefix}{count}.txt")

[Link](old_path, new_path)

print("Files renamed successfully!")

4. Convert Text to Speech

Converts text into speech using pyttsx3.

import pyttsx3

engine = [Link]()

[Link]("Hello! This is an automated voice.")

[Link]()

5. Automate WhatsApp Messages

Sends WhatsApp messages using pywhatkit.

import pywhatkit

[Link]("+1234567890", "Hello, this is an automated message!", 14, 30)

🔹 Tip: This will open WhatsApp Web at 2:30 PM and send the message.
6. Download YouTube Videos

Downloads YouTube videos using pytube.

from pytube import YouTube

url = "[Link]

yt = YouTube(url)

[Link].get_highest_resolution().download()

print("Download Complete!")

7. Auto Organize Files

Organizes files into folders based on file type.

import os

import shutil

folder_path = "/path/to/downloads"

file_types = {

"Images": [".jpg", ".jpeg", ".png", ".gif"],

"Documents": [".pdf", ".docx", ".txt"],

"Videos": [".mp4", ".mkv"],

"Music": [".mp3", ".wav"]

for file in [Link](folder_path):

file_path = [Link](folder_path, file)

if [Link](file_path):

for folder, extensions in file_types.items():

if [Link](tuple(extensions)):

new_folder = [Link](folder_path, folder)

[Link](new_folder, exist_ok=True)

[Link](file_path, new_folder)
print("Files organized successfully!")

8. Check Internet Speed

Measures internet speed using speedtest-cli.

import speedtest

st = [Link]()

download_speed = [Link]() / 1_000_000

upload_speed = [Link]() / 1_000_000

print(f"Download Speed: {download_speed:.2f} Mbps")

print(f"Upload Speed: {upload_speed:.2f} Mbps")

9. Automate Website Status Check

Checks if a website is up or down.

import requests

url = "[Link]

try:

response = [Link](url)

if response.status_code == 200:

print(f"{url} is UP!")

else:

print(f"{url} is DOWN!")

except [Link]:

print(f"{url} is NOT REACHABLE!")

10. Auto Shutdown PC

Schedules a shutdown in 60 seconds.

import os

[Link]("shutdown /s /t 60") # Windows


# [Link]("shutdown -h +1") # Linux/Mac (1-minute delay)

11. Get Weather Updates

Fetches the current weather for any city using OpenWeatherMap API.

import requests

API_KEY = "your_api_key"

city = "New York"

url = f"[Link]

response = [Link](url).json()

print(f"Weather in {city}: {response['weather'][0]['description']}, {response['main']['temp']}°C")

🔹 Tip: Get an API key from OpenWeather.

Would you like scripts for any specific use case? 😊

Common questions

Powered by AI

The bulk file renaming script in Python works by iterating through all files in a specified directory using os.listdir. For each file, it constructs a new filename with a sequential prefix and changes the file name using os.rename. A potential challenge is dealing with file type recognition and preventing overwriting files if the target filenames already exist. Also, care must be taken to handle directory paths properly to avoid errors, particularly in handling different operating systems' file structures. Code snippet import os, folder_path '/path/to/folder', prefix 'file_', for count, filename in enumerate(os.listdir(folder_path)): old_path = os.path.join(folder_path, filename), new_path = os.path.join(folder_path, f'{prefix}{count}.txt'), os.rename(old_path, new_path), print('Files renamed successfully!').

To securely automate sending emails using Python, you should use the smtplib library for connecting to the Gmail SMTP server along with an App Password instead of your regular Gmail password for enhanced security. Implement the email.message module to construct an email message with the desired content, recipients, and subject. Establish a secure SSL connection to 'smtp.gmail.com' using PORT 465 and log in using your email and App Password. Once logged in, use the send_message method to dispatch the email. Code example: import smtplib, from email.message import EmailMessage, email 'your_email@gmail.com', password 'your_app_password', recipient 'recipient_email@gmail.com', msg = EmailMessage(), msg['Subject'] = 'Automated Email', msg['From'] = email, msg['To'] = recipient, msg.set_content('Hello! This is an automated email.'), with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server: server.login(email, password), server.send_message(msg), send_email(), print('Email sent successfully!').

A Python script can be implemented to check a website's availability by making a simple HTTP GET request using the requests module. If the response has a status code of 200, the website is up; otherwise, it may be down, or unreachable if an exception such as ConnectionError is caught. Code example: import requests, url 'https://example.com', try: response = requests.get(url), if response.status_code == 200: print(f'{url} is UP!'), else: print(f'{url} is DOWN!'), except requests.ConnectionError: print(f'{url} is NOT REACHABLE!').

You can automate extracting the top five news headlines using Python by employing web scraping techniques. Utilize the requests library to fetch content from the website and BeautifulSoup to parse the HTML. The script makes an HTTP GET request to the URL of the news website, and BeautifulSoup is used to parse the HTML and locate the news headlines by identifying tags with a specific class. By iterating over the parsed content, you can extract and print the top five headlines. Code example: import requests, from bs4 import BeautifulSoup, url 'https://news.ycombinator.com/', response = requests.get(url), soup = BeautifulSoup(response.text, 'html.parser'), for idx, item in enumerate(soup.find_all('a', class_='storylink')[:5], start=1): print(f'{idx}. {item.text}').

Python can be used to download YouTube videos via the pytube library, which allows you to select video streams and download them to your local machine. By creating a YouTube object using the video URL, you can call get_highest_resolution().download() to save the video locally. However, downloading videos may contravene YouTube's terms of service, which prohibit downloading content without permission or legal basis. Legal considerations involve ensuring compliance with copyright laws and YouTube policies to avoid infringing on intellectual property rights. Code example: from pytube import YouTube, url 'https://www.youtube.com/watch?v=your_video_id', yt = YouTube(url), yt.streams.get_highest_resolution().download(), print('Download Complete!').

To convert text into speech using Python, the pyttsx3 library is commonly used, which is platform-independent. Initialize the text-to-speech engine with pyttsx3.init(), set the desired properties if necessary (e.g., voice, rate, volume), and call engine.say() with the text to be spoken. Finally, execute engine.runAndWait() to process the speech output. Code example: import pyttsx3, engine = pyttsx3.init(), engine.say('Hello! This is an automated voice.'), engine.runAndWait().

To automatically organize files based on their type in a directory, use the os and shutil libraries in Python. Define mappings of file types to their respective directory names. Iterate over the files in the target directory; for each file, use its extension to determine its type. If a file matches a particular type, move it to the designated directory for that type, creating the directory if it doesn't exist. Code example: import os, import shutil, folder_path '/path/to/downloads', file_types { 'Images': ['.jpg', '.jpeg', '.png', '.gif'], 'Documents': ['.pdf', '.docx', '.txt'], 'Videos': ['.mp4', '.mkv'], 'Music': ['.mp3', '.wav'] }, for file in os.listdir(folder_path): file_path = os.path.join(folder_path, file), if os.path.isfile(file_path): for folder, extensions in file_types.items(): if file.endswith(tuple(extensions)): new_folder = os.path.join(folder_path, folder), os.makedirs(new_folder, exist_ok=True), shutil.move(file_path, new_folder), print('Files organized successfully!').

To measure and report internet speed using Python, you can use the speedtest-cli module. This allows you to determine both download and upload speeds. First, instantiate an object of Speedtest class, and call its download and upload functions, which will return the speeds in bits per second. Convert these values to megabits per second by dividing by 1,000,000, and print the results. Code example: import speedtest, st = speedtest.Speedtest(), download_speed = st.download() / 1,000,000, upload_speed = st.upload() / 1,000,000, print(f'Download Speed: {download_speed:.2f} Mbps'), print(f'Upload Speed: {upload_speed:.2f} Mbps').

Python can automate sending messages via WhatsApp using the pywhatkit library, which leverages WhatsApp Web to send messages at a scheduled time. The script opens the web interface in a browser at the specified time and sends the message to a given phone number. One limitation is that this requires the user to be logged in to WhatsApp Web on the browser, and the system must be running (not in sleep mode) to execute the script at the scheduled time. Code example: import pywhatkit, pywhatkit.sendwhatmsg('+1234567890', 'Hello, this is an automated message!', 14, 30), where it schedules sending the message at 2:30 PM .

When automating tasks like shutting down a computer using Python, considerations should include user data loss, permissions, and platform-specific command syntax. Before scheduling a shutdown using os.system, ensure critical data is saved or notify users to do so, as unsaved work might be lost. On Windows, use the command 'shutdown /s /t 60' to delay shutdown by 60 seconds, while on Linux/Mac, 'shutdown -h +1' delays it by one minute. Besides syntax differences, permissions may vary, requiring administrator privileges to execute shutdown commands, impacting the script's effectiveness if not properly handled .

You might also like