[Python] Use the os library and the xlrd library to modify the file name in batches according to the excel list

Problem Description:

It is known that there is a folder containing several pictures named according to the format: ID card number_name. There is a form to record the ID number, name and student number. Now you need to find the corresponding student number in the form according to the ID number above the image file name, and rename the file to: student number_name, and the format is required to be .jpg.

The contents of the folder are as follows:

The content of the excel table is as follows:

 Code:

import os
import xlrd

# 图片所在的路径
img_path = r"D:\素材"
# excel表路径(注意不支持.xlsx)
xlsx_path = r"D:\批量处理测试.xls"
# 读取excel表:批量处理测试.xlsx
xlsx1 = xlrd.open_workbook(xlsx_path)
# 读取表格里第一个sheet(工作簿)
sheet = xlsx1.sheet_by_index(0)

# 获取表格第一列数据
one_col_list = sheet.col_values(0)
# 获取表格第三列数据
three_col_list = sheet.col_values(2)

# 获取该文件夹下所有的文件(包括文件夹)
file_names = os.listdir(img_path)

for file_name in file_names:
    catalog = os.path.join(img_path, file_name)  # 获取所有文件的路径
    if os.path.isdir(catalog):  # os.path.isdir判断是不是目录;跳过目录
        continue
    # 获取文件名的前18位(也就是获取身份证号码)
    id = file_name[:18]
    if id in one_col_list:
        # 获取表格中,相应身份证号码的学号
        corresponding = three_col_list[one_col_list.index(id)]
        # 将文件名更新为学号_姓名
        new_file_name = str(int(corresponding))+file_name[18:22]
        # 重命名
        os.renames(os.path.join(img_path, file_name), os.path.join(img_path, new_file_name)+'.jpg')

Realize the effect:

 

Guess you like

Origin blog.csdn.net/zhou_ge1/article/details/127526248
Recommended