最近比较苦恼批量修改文件的名字,文件名字还要根据表格对应进行修改,最近刚接触python,所以想到利用python读取excel文件对文件自动化的进行改名,以下就开始进行尝试。
# -*- coding: utf-8 -*-
import xlrd
import os
path_c = ".\\photos"
xlsname = "regulation.xls"
bk = xlrd.open_workbook(xlsname)
#shxrange = range(bk.nsheets)
try:
sh = bk.sheet_by_name("Sheet1")
except:
print "no sheet in %s named Sheet1" % xlsname
nrows = sh.nrows
ncols = sh.ncols
print "nrows %d, ncols %d" % (nrows,ncols)
#cell_value = sh.cell_value(1,1)
#print cell_value
row_list = []
#获取各行数据
for i in range(1,nrows):
row_data = sh.row_values(i)
row_list.append(row_data)
#print row_data
def change_name(filename,regulations):
for i in regulations:
print repr(i[0]) + repr(filename)
if i[0].encode("gbk") == filename:#excel中的字符串为unicode,而文件字符串为gbk
return i[1]
return filename
def rename_file(path,regulations):
filelist=os.listdir(path)#该文件夹下所有的文件(包括文件夹)
for files in filelist:
#print files
Olddir=os.path.join(path,files)#原来的文件路径
if os.path.isdir(Olddir):#如果是文件夹,递归地进行修改
rename_file(Olddir,regulations)
continue
filename_old = os.path.splitext(files)[0]#文件名
filetype_old = os.path.splitext(files)[1]#文件扩展名
Newdir = os.path.join(path,change_name(filename_old,regulations)+filetype_old)
print Olddir+"--->"+Newdir
os.rename(Olddir,Newdir)#重命名
rename_file(path_c,row_list)
总的来说主要分为两部分,读取excel表格,修改文件名。主要问题出现在编码问题上,在字符串比较时确定两边是同一编码,详情见参考文献。
reference
python读写excel: http://www.jb51.net/article/42635.htm
python文件重命名: http://blog.csdn.net/risemypassion/article/details/44561451
python 编码详解: http://python.jobbole.com/82107/