python读写excel的图片_python解析excel中图片+提取图片

importos,shutilimportzipfile#判断是否是文件和判断文件是否存在

defisfile_exist(file_path):if notos.path.isfile(file_path):print("It's not a file or no such file exist ! %s" %file_path)returnFalseelse:returnTrue#修改指定目录下的文件类型名,将excel后缀名修改为.zip

def change_file_name(file_path, new_type='.zip'):if notisfile_exist(file_path):return ''extend= os.path.splitext(file_path)[1] #获取文件拓展名

if extend != '.xlsx' and extend != '.xls':print("It's not a excel file! %s" %file_path)returnFalse

file_name= os.path.basename(file_path) #获取文件名

new_name = str(file_name.split('.')[0]) + new_type #新的文件名,命名为:xxx.zip

dir_path= os.path.dirname(file_path) #获取文件所在目录

new_path = os.path.join(dir_path, new_name) #新的文件路径

ifos.path.exists(new_path):

os.remove(new_path)

os.rename(file_path, new_path)#保存新文件,旧文件会替换掉

return new_path #返回新的文件路径,压缩包

#解压文件

defunzip_file(zipfile_path):if notisfile_exist(zipfile_path):returnFalseif os.path.splitext(zipfile_path)[1] != '.zip':print("It's not a zip file! %s" %zipfile_path)returnFalse

file_zip= zipfile.ZipFile(zipfile_path, 'r')

file_name= os.path.basename(zipfile_path) #获取文件名

zipdir = os.path.join(os.path.dirname(zipfile_path), str(file_name.split('.')[0])) #获取文件所在目录

for files infile_zip.namelist():

file_zip.extract(files, os.path.join(zipfile_path, zipdir))#解压到指定文件目录

file_zip.close()returnTrue#读取解压后的文件夹,打印图片路径

defread_img(zipfile_path,img_path):if notisfile_exist(zipfile_path):returnFalse

dir_path= os.path.dirname(zipfile_path) #获取文件所在目录

file_name = os.path.basename(zipfile_path) #获取文件名

unzip_dir = os.path.join(dir_path, str(file_name.split('.')[0]))

pic_dir= 'xl' + os.sep + 'media' #excel变成压缩包后,再解压,图片在media目录

pic_path = os.path.join(dir_path, str(file_name.split('.')[0]), pic_dir)

file_list=os.listdir(pic_path)for file infile_list:

filepath=os.path.join(pic_path, file)print(filepath,img_path)

shutil.move(filepath,img_path)

os.unlink(zipfile_path)

shutil.rmtree(unzip_dir)#组合各个函数

defcompenent(excel_file_path,img_path):

zip_file_path=change_file_name(excel_file_path)if notos.path.exists(img_path):

os.mkdir(img_path)if zip_file_path != '':

unzip_msg=unzip_file(zip_file_path)ifunzip_msg:

read_img(zip_file_path,img_path)#main

if __name__ == '__main__':#excel地址

excel_path = 'C:\\Users\\SHEIN\\Desktop\\test\img.xlsx'

#图片目录

img_dir = 'C:\\Users\\SHEIN\\Desktop\\test\\imgage'compenent(excel_path,img_dir)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值