Python压缩指定文件夹下的所有文件

# -*- coding: utf-8 -*-
import sys
import os.path
import zipfile

defaultencoding = 'utf-8'
 
# if sys.getdefaultencoding() != defaultencoding:
#     reload(sys)
#     sys.setdefaultencoding(defaultencoding)

# 类这里要加个括号
class FileToZip():
    def addZip(self, _reportDate=None):

        dir_name = _reportDate
        # 被压缩文件的路径
        _dataPath = os.path.dirname(os.path.abspath(__file__))
        filePath = _dataPath + f"\\{dir_name}\\"
        outFullName = _dataPath + f'\\{_reportDate}数据.zip'

        # 压缩后输出保存路径
        f = zipfile.ZipFile(outFullName, 'w', zipfile.ZIP_DEFLATED)

        print('被压缩文件的路径:' + filePath)
        for dirpath, dirnames, filenames in os.walk(filePath):
            # 去掉目标跟路径,只对目标文件夹下边的文件及文件夹进行压缩
            # 将当前目录替换为空,即以当前目录为相对目录,如果当前目录下面还存在文件夹,则fpath为 【/子目录】
            fpath = dirpath.replace(dirpath, '')
            for filename in filenames:
                f.write(os.path.join(dirpath, filename),
                        os.path.join(fpath, filename))  # 要添加到压缩文件中的文件路径,添加到压缩文件中的保存的文件名称
        f.close()
 
# if __name__ == "__main__":
#     FileToZip().addZip('2020-05')

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章