python模块zipfile在linux环境中对文件压缩、解压

一,导入相关压缩模块

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"))
	# 生成待处理的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", ""))
	# ZipFile.namelist(): 获取ZIP文档内所有文件的名称列表
    for fileM in zFile.namelist():
		# 将压缩文件里的每个文件解压放入文件夹中
        zFile.extract(fileM, file_dir.replace(".docx", "")
    # 关闭zFile对象
    zFile.close();
    # 删除.zip文件
    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()
    # print(dirpath)
    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))

猜你喜欢

转载自blog.csdn.net/TFATS/article/details/106136500