Fundamentals 9 min read

Python Task Automation: File Renaming, Email Sending, Excel Processing, and Scheduling

This article introduces Python task automation, demonstrating how to batch rename files, send emails, process Excel spreadsheets, and schedule recurring jobs using standard libraries and third‑party modules, while providing best‑practice tips and hands‑on exercises for efficient scripting.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Task Automation: File Renaming, Email Sending, Excel Processing, and Scheduling

Python can act as a powerful "programming robot" to automate repetitive tasks such as batch renaming files, sending scheduled emails, processing Excel data, and running periodic jobs. This tutorial walks through each scenario with clear explanations and ready‑to‑run code examples.

What Is Task Automation?

Task automation means using programs to replace manual effort for repetitive work, for example:

Sending emails on a schedule;

Batch downloading or uploading files;

Automatically processing data files (Excel, CSV, etc.);

Periodically scraping web content.

Python’s extensive standard library and third‑party ecosystem make it an ideal language for these tasks.

Part 1: Starting with Simple Tasks

1. Automatic File Renaming

Suppose you have many files named file1.txt , file2.txt , … and you want to rename them to a uniform pattern like document_1.txt , document_2.txt , etc.

<code>import os

# Get all files in the current directory
files = os.listdir()

# Iterate and rename .txt files
for i, file in enumerate(files):
    if file.endswith(".txt"):
        new_name = f"document_{i+1}.txt"
        os.rename(file, new_name)
        print(f"{file} 已重命名为 {new_name}")
</code>

After running, all .txt files are renamed sequentially to document_1.txt , document_2.txt , …

2. Automatic Email Sending

To send a daily report to your boss with a single script:

<code>import smtplib
from email.mime.text import MIMEText

# Email configuration
smtp_server = "smtp.example.com"
port = 587
sender_email = "[email protected]"
password = "your_password"
receiver_email = "[email protected]"

# Create the email
subject = "今日工作汇报"
body = "今天的工作已经完成,请查收!"
message = MIMEText(body, "plain", "utf-8")
message["Subject"] = subject
message["From"] = sender_email
message["To"] = receiver_email

# Send the email
try:
    server = smtplib.SMTP(smtp_server, port)
    server.starttls()
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message.as_string())
    print("邮件发送成功!")
except Exception as e:
    print(f"邮件发送失败:{e}")
finally:
    server.quit()
</code>

Part 2: Automating Excel Files

Processing Excel spreadsheets is a common workplace task. The openpyxl library enables reading, modifying, and creating Excel files.

Example: Generating Payroll Statements

Given an employees.xlsx file with columns Name and Salary , the script creates a separate text payroll for each employee.

<code>import openpyxl

# Open the workbook
workbook = openpyxl.load_workbook("employees.xlsx")
sheet = workbook.active

# Iterate rows starting from the second (skip header)
for row in sheet.iter_rows(min_row=2, values_only=True):
    name, salary = row
    with open(f"{name}_工资单.txt", "w", encoding="utf-8") as file:
        file.write(f"尊敬的{name}:\n")
        file.write(f"您的月薪为:{salary}元\n")
        file.write("请核对信息并确认。\n")
    print(f"{name} 的工资单已生成!")
</code>

The script produces files such as 张三_工资单.txt containing a personalized payroll statement.

Part 3: Scheduling Tasks

For jobs that need to run at specific times, the schedule library provides a simple declarative API.

Example: Print Current Time Every Minute

<code>import schedule
import time
from datetime import datetime

# Define the job
def job():
    print(f"当前时间:{datetime.now()}")

# Schedule every minute
schedule.every(1).minutes.do(job)

# Keep the script running
while True:
    schedule.run_pending()
    time.sleep(1)
</code>

Best‑Practice Reminders

Security: Never hard‑code sensitive data like passwords; use environment variables or encrypted storage.

Error Handling: Wrap I/O and network calls in try...except blocks to gracefully handle failures.

Permissions & Scheduling: Some automation scripts require admin rights or OS‑level schedulers (cron, Windows Task Scheduler).

Hands‑On Exercises

Write a script that renames all image files (e.g., .jpg ) in a directory based on their capture timestamps.

Write a script that fetches weather data from an API and emails a daily forecast each morning.

Write a script that splits a multi‑sheet Excel workbook into separate files, each containing a single sheet.

Conclusion

We have explored how Python can automate mundane tasks—from renaming files and sending emails to processing Excel data and scheduling recurring jobs. Automation not only boosts productivity but also frees you to focus on creative problem‑solving.

Happy coding, and feel free to experiment with the examples above!

PythonAutomationschedulingExcelEmailfile-renaming
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.