A Collection of Python Automation Scripts for Clipboard Management, Code Quality Checking, File Integrity Verification, Stock Forecasting, Image Downloading, Port Scanning, Password Management, Email Sending, README Generation, and File Organization
This article presents a curated set of Python automation scripts covering clipboard management, code quality analysis, file integrity checks, stock price forecasting, bulk image downloading, network port scanning, secure password storage, mass email dispatch, README file creation, and intelligent file organization, each accompanied by concise explanations and ready‑to‑run code examples.
The article begins with a call to follow a public account for daily Python tips, then introduces a series of practical Python automation scripts.
/01/ Clipboard Manager
A Tkinter‑based GUI monitors the system clipboard using the pyperclip library and stores each copied text entry in a listbox for easy retrieval.
<code>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 GUI setup) ...
root.mainloop()</code>Application
Capture research notes from various sources and categorize them.
Extend to capture calendar events, reminders, passwords, etc.
/02/ Code Quality Checker
This script uses Pylint and Flake8 to automatically analyze Python files in a given directory, reporting style violations and potential bugs.
<code>import os
import subprocess
def analyze_code(directory):
python_files = [file for file in os.listdir(directory) if file.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")
</code>Application
Capture research notes from various sources and categorize them.
Extend to capture calendar events, reminders, passwords, etc.
/03/ File Integrity Checker
Computes the SHA‑256 hash of a file and compares it with an expected checksum to detect tampering.
<code>import hashlib, 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.")
</code>/04/ Smart Trade (Stock Forecast)
Uses the Prophet library together with yfinance and Streamlit to fetch historical stock data and forecast future prices for selected tickers.
<code>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
# ... (plotting and forecasting code) ...
</code>Application
Algorithmic trading dashboard.
Stock price comparison visualisation.
/05/ Automatic Image Downloader
Downloads a specified number of images for a given keyword using the simple_image_download package.
<code>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)
</code>/06/ Port Scanner
Scans a target host for a list of common ports and reports any open ports together with known associated vulnerabilities.
<code>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)
result = sock.connect_ex((target, port))
if result == 0:
open_ports.append(port)
sock.close()
except KeyboardInterrupt:
sys.exit()
except socket.error:
pass
return open_ports
# ... (display table) ...
</code>/07/ Password Manager
A Streamlit web app that encrypts passwords with a hard‑coded Fernet key, stores them in a CSV file, and can retrieve and decrypt them after key verification.
<code>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(token):
try:
return Fernet(CUSTOM_ENCRYPTION_KEY).decrypt(token).decode()
except InvalidToken:
return "Invalid Token"
# UI for saving and retrieving passwords follows …
</code>/08/ Email Bulk Sender
Uses SMTP over SSL to send a custom email to a list of recipients; the script is a template for mass‑mailing campaigns.
<code>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 promotional content 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}'.encode()
server.sendmail(from_address, to_address, message)
</code>/09/ README.md Generator
Interactively gathers repository information and generates a formatted README file with badges, installation, usage, contributors, and license sections.
<code>def generate_markdown_file():
repo = input("Enter the name of your GitHub repository: ")
description = input("Enter a short description of your project: ")
# ... collect other fields ...
markdown_content = f"""
# {repo}
{description}
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Contributors](#contributors)
- [License](#license)
- [Badges](#badges)
- [GitHub Repository](#github-repository)
## Installation
```
{install_instructions}
```
## Usage
```
{usage_instructions}
```
## Contributors
{contributors}
## License
This project is licensed under the {license} License.
## Badges
{stars_badge} {forks_badge} {issues_badge} {license_badge}
## GitHub Repository
[Link to GitHub repository](https://github.com/{repo})
"""
with open(f"{repo}_README.md", "w") as f:
f.write(markdown_content)
print(f"Markdown file '{repo}_README.md' generated successfully!")
</code>/10/ OrganizeIT 2.0
Organises files in a directory by extension, moves duplicates to a "Duplicates" folder based on SHA‑256 hashes, and creates sub‑folders for each file type.
<code>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):
extension_folders = {}
duplicates_folder = os.path.join(folder, 'Duplicates')
os.makedirs(duplicates_folder, exist_ok=True)
file_hashes = {}
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
if os.path.isfile(file_path):
_, ext = os.path.splitext(filename)
ext = ext.lower()
dest = extension_folders.get(ext)
if not dest:
dest = os.path.join(folder, 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_path = input("Enter the path to the folder to organize: ")
organize_and_move_duplicates(folder_path)
</code>The article concludes with a QR‑code invitation to scan and receive free Python learning resources, linking to additional articles about niche Python libraries, automation scenarios, SQLite usage in WeChat, and essential decorators.
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.