A Collection of Python Automation Scripts for Clipboard Management, Code Quality, File Integrity, Stock Forecasting, Image Downloading, Port Scanning, Password Management, Email Sending, README Generation, and Folder Organization
This article presents a curated set of Python automation scripts covering clipboard monitoring, code quality analysis, file integrity verification, stock price forecasting, bulk image downloading, network port scanning, encrypted password storage, mass email sending, README.md generation, and intelligent folder organization, each illustrated with complete source code.
This article provides a comprehensive collection of Python automation scripts that demonstrate practical solutions for everyday development and operational tasks.
1. Clipboard Manager – Monitors the system clipboard using pyperclip and displays captured text in a Tkinter GUI.
import tkinter as tk
from tkinter import ttk
import pyperclip
def update_listbox():
new_item = pyperclip.paste()
if new_item not in X:
X.append(new_item)
listbox.insert(tk.END, new_item)
listbox.insert(tk.END, "----------------------")
listbox.yview(tk.END)
root.after(1000, update_listbox)
# ... (rest of the GUI setup) ...
root.mainloop()2. Code Quality Checker – Uses Pylint and Flake8 to automatically analyze Python files in a given directory.
import os
import subprocess
def analyze_code(directory):
python_files = [f for f in os.listdir(directory) if f.endswith('.py')]
if not python_files:
print("No Python files found in the specified directory.")
return
for file in python_files:
file_path = os.path.join(directory, file)
print(f"Analyzing file: {file}")
subprocess.run(f"pylint {file_path}", shell=True)
subprocess.run(f"flake8 {file_path}", shell=True)
if __name__ == "__main__":
analyze_code(r"C:\Path\To\Your\Project")3. File Integrity Checker – Calculates SHA‑256 checksums to verify whether a file has been tampered with.
import hashlib
import os
def calculate_sha256(file_path):
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
sha256.update(chunk)
return sha256.hexdigest()
def check_integrity(file_path, expected_checksum):
return calculate_sha256(file_path) == expected_checksum
if __name__ == "__main__":
path = input("Enter the path to the file: ")
expected = input("Enter the expected SHA-256 checksum: ")
if os.path.isfile(path):
if check_integrity(path, expected):
print("File integrity verified: The file has not been tampered with.")
else:
print("File integrity check failed: The file may have been tampered with.")
else:
print("Error: File not found.")4. Smart Trade (Stock Forecasting) – Retrieves historical stock data with yfinance and forecasts future prices using Facebook's Prophet library, displayed via Streamlit.
import streamlit as st
from datetime import date
import yfinance as yf
from prophet import Prophet
from prophet.plot import plot_plotly
from plotly import graph_objs as go
START = "2015-01-01"
TODAY = date.today().strftime("%Y-%m-%d")
st.title('Stock Forecast App')
stocks = ('MSFT', 'TSLA', 'GOOG', 'AAPL', 'NVDA')
selected_stock = st.selectbox('Select dataset for prediction', stocks)
n_years = st.slider('Years of prediction:', 1, 4)
period = n_years * 365
@st.cache
def load_data(ticker):
data = yf.download(ticker, START, TODAY)
data.reset_index(inplace=True)
return data
# ... (data loading, plotting, forecasting) ...5. Automatic Image Downloader – Downloads a specified number of images for a given keyword using the simple_image_download library.
from simple_image_download import simple_image_download as simp
response = simp.simple_image_download
keyword = "Dog"
try:
response().download(keyword, 20)
print("Images downloaded successfully.")
except Exception as e:
print("An error occurred:", e)6. Port Scanner – Scans the top 15 common ports on a target host and reports known vulnerabilities using socket and prettytable .
import socket
from prettytable import PrettyTable
vulnerabilities = {80: "HTTP – Unencrypted web traffic", 443: "HTTPS – Encrypted web traffic", 22: "SSH – Secure remote access", ...}
def scan_top_ports(target):
open_ports = []
top_ports = [21,22,23,25,53,80,110,143,443,3306,3389,5900,8000,8080,8443]
for port in top_ports:
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
if sock.connect_ex((target, port)) == 0:
open_ports.append(port)
sock.close()
except KeyboardInterrupt:
sys.exit()
except socket.error:
pass
return open_ports
# ... (display results with PrettyTable) ...7. Password Manager – Stores website credentials in an encrypted CSV file using cryptography.Fernet and provides a Streamlit UI for saving and retrieving passwords.
import streamlit as st
import csv
from cryptography.fernet import Fernet, InvalidToken
CUSTOM_ENCRYPTION_KEY = b'u7wGgNdDFefqpr_kGxb8wJf6XRVsRwvb3QgITsD5Ft4='
def encrypt_password(pw):
return Fernet(CUSTOM_ENCRYPTION_KEY).encrypt(pw.encode())
def decrypt_password(enc):
try:
return Fernet(CUSTOM_ENCRYPTION_KEY).decrypt(enc).decode()
except InvalidToken:
return "Invalid Token"
# Streamlit UI for saving and retrieving passwords ...8. Email Bulk Sender – Sends mass emails through Gmail's SMTP server with SSL/TLS encryption.
import smtplib, ssl
smtp_server = 'data.STUDIO.com'
smtp_port = 465
from_address = 'Winzo Shop'
to_address = ['', '']
username = ''
password = ''
subject = '🎉 Exclusive Offer Inside! Get 10% Off Your Next Purchase'
body = '''Your email body here'''
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, smtp_port, context=context) as server:
server.set_debuglevel(1)
server.login(username, password)
message = f'From: {from_address}\r\nSubject: {subject}\r\nTo: {to_address}\r\n\r\n{body}'
server.sendmail(from_address, to_address, message.encode())9. README.md Generator – Interactively creates a README file for a GitHub repository based on user input, including badges for stars, forks, issues, and license.
def generate_markdown_file():
repo = input("Enter repository name: ")
desc = input("Enter short description: ")
# ... collect other fields ...
markdown = f"""
# {repo}
{desc}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- ...
"""
with open(f"{repo}_README.md", "w") as f:
f.write(markdown)
if __name__ == "__main__":
generate_markdown_file()10. OrganizeIT 2.0 – Organizes files in a directory by extension, moves duplicates to a dedicated folder using SHA‑256 hashes, and prints actions performed.
import os, hashlib, shutil
def get_file_hash(path):
with open(path, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
def organize_and_move_duplicates(folder_path):
extension_folders = {}
duplicates_folder = os.path.join(folder_path, 'Duplicates')
os.makedirs(duplicates_folder, exist_ok=True)
file_hashes = {}
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
if os.path.isfile(file_path):
_, ext = os.path.splitext(filename)
ext = ext.lower()
dest = extension_folders.get(ext, os.path.join(folder_path, ext[1:]))
os.makedirs(dest, exist_ok=True)
extension_folders[ext] = dest
file_hash = get_file_hash(file_path)
if file_hash in file_hashes:
shutil.move(file_path, os.path.join(duplicates_folder, filename))
print(f"Moved duplicate file {filename} to Duplicates folder.")
else:
file_hashes[file_hash] = filename
shutil.move(file_path, dest)
print(f"Moved {filename} to {dest}")
if __name__ == "__main__":
folder = input("Enter the path to the folder to organize: ")
organize_and_move_duplicates(folder)Each script is self‑contained, ready to run after installing the required third‑party packages (e.g., pip install pyperclip tkinter pylint flake8 yfinance prophet streamlit cryptography prettytable simple_image_download ), and demonstrates how Python can automate routine tasks across development, security, data analysis, and productivity domains.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.