一,导入相关压缩模块
import shutil
import zipfile
二,对处理文件路径进行分割处理
(filepath, tempfilename) = os.path.split(target_dir)
(docx_name, extension) = os.path.splitext(tempfilename)
三,如果拷贝处理文件并更改修改其后缀名
shutil.copyfile(target_dir, file_dir.replace(".docx", ".zip"))
四,实现对目标文件的压缩、解压
def unzipDir(target_dir,file_dir):
shutil.copyfile(target_dir, file_dir.replace(".docx", ".zip"))
zFile = zipfile.ZipFile(file_dir.replace(".docx", ".zip"), "r")
if os.path.exists(file_dir.replace(".docx", "")) == False:
os.makedirs(file_dir.replace(".docx", ""))
for fileM in zFile.namelist():
zFile.extract(fileM, file_dir.replace(".docx", "")
zFile.close();
os.remove(file_dir.replace(".docx", ".zip"))
def zipDir(dirpath, outFullName):
zip = zipfile.ZipFile(outFullName, "w", zipfile.ZIP_DEFLATED)
for path, dirnames, filenames in os.walk(dirpath):
fpath = path.replace(dirpath, '')
for filename in filenames:
zip.write(os.path.join(path, filename), os.path.join(fpath, filename))
zip.close()
shutil.rmtree(dirpath)
if __name__ == "__main__":
current_dir = os.getcwd()
file_dir = current_dir + "/utils/structure_modify/files_space/"
(filepath, tempfilename) = os.path.split(target_dir)
(docx_name, extension) = os.path.splitext(tempfilename)
unzipDir(target_dir, file_dir+tempfilename)
unzip_string = file_dir + docx_name
outFullName = file_dir + tempfilename
zipDir(unzip_string, outFullName)
os.system("mv %s %s"%(outFullName,target_dir))