????????接了一个需求,需要将批量图片按照指定的需求进行重命名,本来的图片是以身份证号进行命名的.jpg文件,现在需要统一命名为班级+姓名+身份证号.png格式的文件。其中,用户提供了一张导出的excel数据表(data.xlsx),数据表对应的信息有四列,分别是班级、序号、姓名和身份证号。
????????考虑使用python中的excel相关的操作函数对数据进行处理,然后结合相关的操作来完成。
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 17 20:23:57 2021
@author: Pegasus
"""
import xlrd
book = xlrd.open_workbook('data.xls')
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
ncols = sheet1.ncols
d={}
for i in range(nrows):
d[sheet1.row_values(i)[3]]=sheet1.row_values(i)[2]
row3_values = sheet1.row_values(2)
print('第3行值',row3_values)
col3_values = sheet1.col_values(2)
print('第3列值',col3_values)
cell_3_3 = sheet1.cell(2,2).value
print('第3行第3列的单元格的值:',cell_3_3)
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 17 20:10:42 2021
@author: Pegasus
"""
import os
import xlrd
book = xlrd.open_workbook('data.xls')
sheet1 = book.sheets()[0]
nrows = sheet1.nrows
d={}
for i in range(nrows):
d[sheet1.row_values(i)[3]]=sheet1.row_values(i)[2]
class BatchRename():
def __init__(self, path):
self.path = path
def rename(self):
filelist = os.listdir(self.path)
for item in filelist:
ID = item.split('.')[0]
name = d[ID]
if item.endswith('.jpg'):
src = os.path.join(os.path.abspath(self.path), item)
print('src',src)
dst = os.path.join(os.path.abspath(self.path), '' + name+'-'+ID + '.png')
try:
os.rename(src, dst)
print('converting %s to %s ...' % (src, dst))
except:
continue
if __name__ == '__main__':
path = './img'
demo = BatchRename(path)
demo.rename()