[Python] 利用os库和xlrd库实现根据excel清单批量修改文件名

问题描述:

已知有一文件夹存放着若干按照:身份证号码_姓名格式命名的图片。有一表格里记录身份证号码、姓名和学号。现在需要根据图片文件名上面的身份证号码去寻找表格里相应的学号,并将文件重命名为:学号_姓名,要求为.jpg格式。

文件夹内容如下:

excel表格内容如下:

 代码实现:

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')

实现效果:

 

猜你喜欢

转载自blog.csdn.net/zhou_ge1/article/details/127526248