Fundamentals 5 min read

How to Automate File Renaming and Deletion with Python: Practical Scripts

This article walks through practical Python scripts for automating office tasks, showing how to batch‑rename files based on folder names and safely delete unwanted files, complete with code examples, execution tips, and best practices for sharing concise snippets in community groups.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Automate File Renaming and Deletion with Python: Practical Scripts

1. Introduction

Hello, I'm PiPi. Recently a question was asked in a Python community about automating office tasks with Python. The question was how to determine whether folder names contain "Branch" or "Marketing Center". Below are the solutions.

2. Implementation

Two code examples were provided. The first demonstrates batch renaming based on a predefined name list:

name = ["张三", "李四", "王虎", "老六", "二虎"]
file_name = os.listdir(r"C:\Users\pdcfi\Desktop\绩效")
for n in name:
    for file in file_name:
        if n in file:
            os.rename("C:/Users/Desktop/绩效/" + file, "C:/Users/Desktop/绩效/" + n + "8月绩效.xlsx")
            print(f"{n}已经替换完成!")

The second example shows how to delete files whose names contain a specific keyword:

def delete_file(path):
    # (root, dirs, files) represent the current folder, subfolders, and files
    for root, dirs, files in os.walk(path):
        for file in files:
            if "_双章" in file:  # additional condition
                os.remove(file)
                print(f'{file} 文件删除成功')
if __name__ == '__main__':
    source_path = r'D:\供应链\订单&需求单'
    target_path = r'C:\Users\Desktop\待制作'
    delete_file(target_path)

These scripts iterate through directories, check conditions, and perform the required renaming or deletion, effectively solving the user's problem.

3. Summary

This article presented a Python automation scenario, provided clear code implementations for batch file renaming and conditional file deletion, and offered practical advice for sharing concise code snippets when seeking help in community groups. When asking questions in groups, it is recommended to provide sanitized demo data, include error screenshots, and share code directly if short; for longer scripts, attach a .py file.

scriptingfile deletionFile Automationbatch renaming
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

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.