Fundamentals 10 min read

10 Practical Python Scripts for Automation and Everyday Tasks

This article presents ten ready‑to‑use Python scripts covering file renaming, web image downloading, automated email sending, password generation, Excel processing, image compression, weather querying, PDF merging, text‑to‑speech conversion, and a simple Snake game, each with clear code examples and usage tips.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
10 Practical Python Scripts for Automation and Everyday Tasks

Looking for quick Python utilities? Below are ten concise scripts that solve common problems, each accompanied by a short description, the core code wrapped in tags, and practical tips.</p> <h2>1. Batch Rename Files (Office Tool)</h2> <p><strong>Scenario:</strong> Rename dozens of files automatically.</p> <code>import os path = "D:\\Files" # replace with your folder path for i, filename in enumerate(os.listdir(path)): os.rename(f"{path}/{filename}", f"{path}/文件_{i+1}.txt") Effect: Files become "文件_1.txt", "文件_2.txt", … Tips: Use double backslashes on Windows, single slashes on macOS/Linux. 2. One‑Click Download Web Images (Crawler Intro) Scenario: Save all images from a webpage. import requests from bs4 import BeautifulSoup url = "https://example.com" # replace with target page response = requests.get(url) soup = BeautifulSoup(response.text, "html.parser") for img in soup.find_all("img"): img_url = img.get("src") if img_url.startswith("http"): with open(img_url.split("/")[-1], "wb") as f: f.write(requests.get(img_url).content) Effect: All images are saved locally. Tips: Install dependencies with pip install requests beautifulsoup4 ; adjust for complex sites. 3. Automatic Email Sending (Work Efficiency) Scenario: Send daily reports automatically. import smtplib from email.mime.text import MIMEText msg = MIMEText("这是邮件正文", "plain", "utf-8") msg["Subject"] = "自动邮件标题" msg["From"] = "你的邮箱@qq.com" msg["To"] = "目标邮箱@163.com" with smtplib.SMTP_SSL("smtp.qq.com", 465) as server: server.login("你的邮箱@qq.com", "邮箱授权码") server.send_message(msg) Effect: Sends the email with one command. Tips: QQ mail requires an authorization code, not the login password. 4. Random Password Generator (Secure & Fun) Scenario: Create a strong password for new accounts. import random, string length = 12 chars = string.ascii_letters + string.digits + string.punctuation password = "".join(random.choice(chars) for _ in range(length)) print(f"你的新密码:{password}") Effect: Generates a 12‑character password containing letters, numbers, and symbols. Tips: Adjust length as needed for higher security. 5. Excel Automation (Data Lover's Favorite) Scenario: Process hundreds of rows without manual effort. import pandas as pd df = pd.read_excel("你的文件.xlsx") df["新列"] = df["旧列"] * 2 # example: double the values df.to_excel("新文件.xlsx", index=False) Effect: Reads, transforms, and saves the Excel file. Tips: Install with pip install pandas openpyxl and adjust column names. 6. Batch Image Compression (Save Space) Scenario: Reduce size of many photos. from PIL import Image import os path = "D:\\Pictures" # image folder for filename in os.listdir(path): if filename.endswith(".jpg"): img = Image.open(f"{path}/{filename}") img.resize((800, 600)).save(f"{path}/压缩_{filename}", quality=85) Effect: Images are resized to 800×600 with 85% quality. Tips: Install Pillow via pip install Pillow and customize dimensions. 7. Weather Query Script (Life Assistant) Scenario: Quickly check tomorrow's weather. import requests city = "Beijing" # replace with city name in English url = f"http://wttr.in/{city}?format=%C+%t" response = requests.get(url) print(f"{city}天气:{response.text}") Effect: Prints something like "Beijing天气:Sunny +15°C". Tips: Uses a free API, no registration required. 8. PDF Merger Tool (Document Organization) Scenario: Combine multiple PDFs into one. from PyPDF2 import PdfMerger merger = PdfMerger() for pdf in ["文件1.pdf", "文件2.pdf"]: # replace with actual filenames merger.append(pdf) merger.write("合并后的文件.pdf") merger.close() Effect: Produces a single merged PDF. Tips: Install with pip install PyPDF2 and ensure correct file names. 9. Text‑to‑Speech Conversion (Creative Play) Scenario: Turn text into an audio file. from gtts import gTTS text = "你好,我是Python小助手" tts = gTTS(text=text, lang="zh-CN") tts.save("output.mp3") Effect: Generates "output.mp3" containing the spoken text. Tips: Install with pip install gtts ; supports many languages. 10. Simple Snake Game (Relax) Scenario: Play a quick game after work. import pygame pygame.init() screen = pygame.display.set_mode((600, 400)) snake = [(200, 200)] direction = (20, 0) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() snake.append((snake[-1][0] + direction[0], snake[-1][1] + direction[1])) snake.pop(0) screen.fill((0, 0, 0)) for pos in snake: pygame.draw.rect(screen, (0, 255, 0), (*pos, 20, 20)) pygame.display.flip() pygame.time.delay(100) Effect: A basic green snake moves on a black background. Tips: Install pygame via pip install pygame ; extend with food and keyboard controls. Which script fits your need? Try them out and feel free to leave comments for any questions.

Pythonautomationscriptingcode snippetsutilitiesBeginner
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.