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')

 

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