Fundamentals 10 min read

10 Practical Python Scripts to Boost Your Productivity

Discover ten highly useful Python scripts covering tasks such as batch file renaming, web image downloading, automated emailing, password generation, Excel data processing, image compression, weather querying, PDF merging, text-to-speech conversion, and a simple Snake game, each with code, explanation, and tips.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
10 Practical Python Scripts to Boost Your Productivity

Python is a versatile language for everyday tasks. This article presents ten ready‑to‑use scripts that can automate common workflows, ranging from file management to simple games.

1. Batch rename files (office tool)

Scenario: Rename dozens of files in a folder without manual effort.

<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")
</code>

Effect: Files are renamed to “文件_1.txt”, “文件_2.txt”, …

Tips: Use double backslashes on Windows, single slash on macOS/Linux.

2. One‑click download webpage images (web scraping starter)

Scenario: Batch‑save images from a website.

<code>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)
</code>

Effect: All images on the page are downloaded locally.

Tips: Install dependencies with pip install requests beautifulsoup4 ; complex sites may need code adjustments.

3. Automatic email sending (work efficiency)

Scenario: Send daily reports to your boss automatically.

<code>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)
</code>

Effect: Sends the email with one command.

Tips: QQ email authorization code is generated in “Settings → Account”, not the login password.

4. Random password generator (secure & fun)

Scenario: Quickly create a strong password for a new account.

<code>import random
import string
length = 12
chars = string.ascii_letters + string.digits + string.punctuation
password = "".join(random.choice(chars) for _ in range(length))
print(f"你的新密码:{password}")
</code>

Effect: Generates a 12‑character password containing letters, digits, and symbols.

Tips: Adjust length as needed; longer passwords increase security.

5. Excel automation (data‑handy)

Scenario: Process hundreds of rows in Excel without manual work.

<code>import pandas as pd
df = pd.read_excel("你的文件.xlsx")
df["新列"] = df["旧列"] * 2  # example: double a column
df.to_excel("新文件.xlsx", index=False)
</code>

Effect: Reads the Excel file, manipulates data, and saves a new file.

Tips: Install dependencies with pip install pandas openpyxl ; adjust column names to match your file.

6. Batch compress images (save space)

Scenario: Reduce the size of many photos.

<code>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)
</code>

Effect: Images are resized to 800×600 with 85% quality.

Tips: Install Pillow via pip install Pillow ; customize dimensions and quality as needed.

7. Weather query script (life assistant)

Scenario: Quickly check tomorrow’s weather.

<code>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}")
</code>

Effect: Prints output like “Beijing天气:Sunny +15°C”.

Tips: Free API, no registration required.

8. PDF merge tool (document organization)

Scenario: Combine multiple PDFs into a single file.

<code>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()
</code>

Effect: Produces one merged PDF.

Tips: Install with pip install PyPDF2 ; ensure file names are correct.

9. Text‑to‑speech conversion (creative use)

Scenario: Turn text into an audio file to share with friends.

<code>from gtts import gTTS
text = "你好,我是Python小助手"
tts = gTTS(text=text, lang="zh-CN")
tts.save("output.mp3")
</code>

Effect: Generates a Chinese voice file named output.mp3 .

Tips: Install with pip install gtts ; supports many languages.

10. Simple Snake game (relaxation)

Scenario: Play a quick game after a long work session.

<code>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)
</code>

Effect: A simple green snake moves on a black background.

Tips: Install pygame via pip install pygame ; full version can add food and keyboard control.

These ten scripts cover a wide range of practical scenarios—from office automation to entertainment—providing ready‑to‑run code, clear explanations, and useful tips to help you get started quickly.

automationproductivityscriptingTutorial
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.