【Python压缩文件夹】导入“zipfile”模块
import zipfile import os def zip_ya(startdir, file_news): z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED) for dirpath, dirnames, filenames in os.walk(startdir): fpath = dirpath.replace(startdir, '') # 这一句很重要,不replace的话,就从根目录开始复制 fpath = fpath and fpath + os.sep or '' for filename in filenames: z.write(os.path.join(dirpath, filename), fpath + filename) print('压缩成功') z.close() if __name__ == '__main__': startdir = r"D:\升级记录\IPTV\2021\12" # 要压缩的文件夹路径 file_news = 'z1.zip' # 压缩后文件夹的名字 zip_ya(startdir, file_news)
【Python解压文件】
import zipfile import os def zip_jie(file_dir, file_news): zipFile = zipfile.ZipFile(file_dir) for file in zipFile.namelist(): zipFile.extract(file, file_news) zipFile.close() if __name__ == '__main__': file_news = r"D:\升级记录\IPTV\2021\12" startdir = 'z1.zip' zip_ya(startdir, file_news)