SoFunction
Updated on 2025-03-04

4 Must-Learn Python Automation Tips

In today's fast-paced work environment, automation is an important means to improve efficiency. As a powerful and easy-to-use programming language, Python has a wide range of applications in the field of automation. This article will introduce 4 must-learn Python automation techniques, which help you quickly master these techniques through concise language, clear logic, practical code and vivid cases, thereby improving work efficiency.

Tips 1: File processing automation

In daily work, processing files is a common task. Python provides rich file processing functions, which can easily read and write files in various formats. By automating file processing, you can save a lot of time and reduce repetitive labor.

Case: Batch rename files

Suppose you have a folder that stores many image files, and their naming formats are not uniform. You want to rename these image files to a unified format, such as "Image Serial Number.jpg".

import os
 
# Set folder pathfolder_path = 'path/to/your/folder'
 
# Get all files in the folderfiles = (folder_path)
 
# Filter out image files (end with .jpg)image_files = [f for f in files if ('.jpg')]
 
# Rename the filefor i, file_name in enumerate(image_files, start=1):
    new_file_name = f'{i}.jpg'
    old_file_path = (folder_path, file_name)
    new_file_path = (folder_path, new_file_name)
    (old_file_path, new_file_path)
 
print('File renaming is complete!  ')

After running the above code, all .jpg files in the folder will be renamed to "", "", etc. This simple script greatly simplifies the process of batch renaming files.

Tips 2: Network request automation

Network requests are an integral part of the fields of data analysis and crawling. Python's requests library can easily initiate HTTP requests and obtain web page data. By automating network requests, you can easily get the information you need from the internet.

Case: Get web page content and save it as a file

Suppose you want to get the content of a certain web page and save it as a local file.

import requests
 
# Set the target URLurl = ''
 
# Initiate HTTP GET requestresponse = (url)
 
# Check whether the request is successfulif response.status_code == 200:
    # Get web content    web_content = 
    
    # Set the save path and file name    save_path = 'path/to/save/'
    
    # Write web page content to a file    with open(save_path, 'w', encoding='utf-8') as file:
        (web_content)
    
    print('The content of the web page has been saved as a file!  ')
else:
    print(f'Request failed,Status code:{response.status_code}')

This script initiates an HTTP GET request through the requests library, obtains the content of the destination web page, and saves it as a local HTML file. You can modify the URL and save path as needed to obtain and save the content of different web pages.

Tips 3: Timed task automation

In automated scripts, certain tasks are sometimes required to be performed regularly. Python's schedule library allows you to easily set up timed tasks, allowing you to execute code at specified times or intervals.

Case: Send email reminders regularly

Suppose you want to send an email to remind yourself of what you are working today at 5 pm every day.

import schedule
import time
import smtplib
from  import MIMEText
 
# Set the email sending functiondef send_email():
    # Email Server Settings    smtp_server = ''
    smtp_port = 587
    sender_email = 'your_email@'
    sender_password = 'your_password'
    
    # Email content settings    receiver_email = 'receiver_email@'
    subject = 'Work Reminder'
    body = 'Today is XX, XX, don't forget to complete the following tasks:...'
    
    # Create a mail object    message = MIMEText(body, 'plain', 'utf-8')
    message['From'] = sender_email
    message['To'] = receiver_email
    message['Subject'] = subject
    
    # Send email    with (smtp_server, smtp_port) as server:
        ()
        (sender_email, sender_password)
        (sender_email, receiver_email, message.as_string())
    
    print('The email has been sent!  ')
 
# Set up timed tasks: Send emails at 5 pm every day().("17:00").do(send_email)
 
# Run timing taskswhile True:
    schedule.run_pending()
    (1)

This script sets a timed task through the schedule library, and calls the send_email function to send emails at 5 pm every day. In the send_email function, use the smtplib library and module to create and send mail. You can modify the mail server settings, sender and receiver mailboxes, and email content as needed.

Tips 4: Data processing automation

Data processing is a core task in areas such as data analysis and machine learning. Python's Pandas library provides powerful data processing capabilities that allow easy reading, cleaning, converting and analyzing data. By automating data processing, you can improve the efficiency and accuracy of data processing.

Case: Cleaning data in CSV files

Suppose you have a CSV file with some missing values ​​and outliers. You want to clean this data, delete missing values ​​and outliers, and save the cleaned data.

import pandas as pd
 
# Read CSV filedf = pd.read_csv('path/to/your/')
 
# View dataprint(())
 
# Delete missing valuesdf_dropna = ()
 
# Delete outliers (assuming the outliers are values ​​less than 0 or greater than 100)df_clean = df_dropna[(df_dropna >= 0) & (df_dropna <= 100)]
 
# Save cleaned datadf_clean.to_csv('path/to/save/cleaned_file.csv', index=False)
 
print('Data cleaning is complete!  ')

This script reads CSV files through the Pandas library, deletes missing values ​​and outliers, and saves the cleaned data as a new CSV file. You can modify the path to read and save files as well as conditions to delete outliers as needed.

Summarize

This article introduces 4 must-learn Python automation techniques: file processing automation, network request automation, timing task automation, and data processing automation. Through these techniques, you can greatly improve your work efficiency and reduce repetitive labor. Each technique is equipped with concise code and vivid cases to help you quickly grasp how it is applied.

In practical applications, you can combine these techniques according to specific needs to build more complex and efficient automated scripts. For example, you can combine file processing with network requests, download files from the Internet and process them; you can also combine timed tasks and data processing to analyze and report data regularly.

In short, Python automation techniques are a powerful tool for improving work efficiency. Through continuous learning and practice, you can master more skills and apply them flexibly at work to achieve better results.

This is the end of this article about 4 must-learn Python automation skills. For more related Python automation skills, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!