[Python 3 to get all the pictures of Word]

Last time I talked about how to manually extract all the pictures in a Word document quickly. This time we use Python-3 based on the principle of image extraction and write code to achieve automatic acquisition.



Python 3 implementation code




import os,zipfile,shutil  #引入os(文件及目录操作)、zipfile(zip文件操作)、shutil(拷贝文件)库def getimage(docdir):  #自定义getimage函数,用于实现Word文档图片获取功能    os.chdir(docdir)    #改变当前工作目录到传递过来的的路径    dirlist = os.listdir(docdir)    #获取该目录下的所有文件夹包含的文件或文件夹的名字的列表    for i in dirlist:        if i.endswith(".docx"): #匹配docx文件            docname = i.split(".") #以“.”做成列表形式            os.rename(i,"%s.ZIP"%docname[0]) #重命名为ZIP格式            f = zipfile.ZipFile("%s.ZIP"%docname[0], 'r')            for file in f.namelist():                if "word" in file:                    f.extract(file)  #将压缩包里的word文件夹解压出来            f.close()            oldimagedir = r"%s\word\media"%docdir #定义图片文件夹            shutil.copytree(oldimagedir,"%s\%s"%(docdir,docname[0])) #拷贝到新目录,名称为word文件的名字            os.rename("%s.ZIP" % docname[0],"%s.docx"% docname[0]) #将ZIP名字还原为DOCX            shutil.rmtree("%s\word"%docdir) #删除word文件夹
if __name__=="__main__":  #主程序入口    getimage('d:\Python_tool\图片比对') #调用图片获取函数,传递目录

The above is the function implementation source code, interested friends can try it by themselves. In addition, the implementation of EXCEL is the same as above, just change .docx to .xlsx.


Guess you like

Origin blog.51cto.com/15069490/2578660