Python renames word files in batches

 

1. Background

        In daily work or study, we may encounter the need to rename a large number of Word files. Manually modifying file names one by one is time-consuming and laborious, but writing a Python script can automate this task and improve efficiency.

2. Development environment

        In order to realize the function of renaming Word files in batches, we can choose to use the Python programming language. Python is an easy-to-use yet powerful scripting language suitable for handling file and directory operations.

In terms of development environments, we recommend the following tools and libraries:

  1. Python interpreter: Make sure you have the latest version of Python properly installed and the correct environment variables set. Use Python3.6 version locally
  2. IDE (Integrated Development Environment): such as PyCharm, Visual Studio Code, etc. IDE can provide code editing, debugging and other functions to make development more efficient and convenient. Use PyCharm2022 locally
  3. Other required libraries: such as os library for file path operations, etc.

3. Code practice

@author:Awen
@file:generate_random_number.py
@time:2023/07/04
"""
import random
import os


def randomStr(length):
#length为字符串长度
    seed = "1234567890abcdefghijklmnopqrstuvwxyz"
    randomStr= []
    for i in range(length):
        randomStr.append(random.choice(seed))
    randomStr= ''.join(randomStr)
    return randomStr


# 定义需要重命名的文件夹路径和统一的前缀名
folder_path = "D:\Pycharmproject2023\code_test_project\data"

# 获取文件夹中的所有文件名
file_names = os.listdir(folder_path)

# 遍历所有文件,进行重命名
i = 1
for file_name in file_names:
    # 获取文件路径和扩展名
    file_path = os.path.join(folder_path, file_name)
    ext = os.path.splitext(file_name)[1]
    # print(ext)
    salt = randomStr(16)
    # 新文件名为前缀名 + 原文件名
    new_file_name = 'c'+''+str(i)+"_"+salt+ext

    # 重命名文件
    os.rename(file_path, os.path.join(folder_path, new_file_name))
    i = i+1

operation result:

 

Guess you like

Origin blog.csdn.net/weixin_40547993/article/details/131671403