搜索此博客

2018年6月27日星期三

Zip files using Python(基于Python压缩文件夹)

# -*- coding: utf-8 -*-
"""
Created on Wed Jun 27 2018

@author: Baikal
"""
#Purpose: To zip unzip folders of Sentinel-1 files and rename zipfile(Mainly to remove this '.SAFE' four characters) 
#         to adapt the python processing.

#利用的是对目录进行深度优先遍历,首先把第一级目录中的文件进行遍历,如果是文件,
#则把它连同当前路径一起加入result(list),如果是子目录,则在整个目录上继续DFS
#直到所有的文件都被加入。


import os
import time
import zipfile

# 迭代判断是否到达根目录 def dfs_get_zip_file(  S1_dir, result ):
    
    id = 0
    files = os.listdir( S1_dir )
    for file in files:
        if os.path.isdir( S1_dir + '/' + file ):
            dfs_get_zip_file( S1_dir + '/'+ file, result )
        else:   
            result.append( S1_dir + '/' + file  )

def zip_path(In_dir, Out_dir):

    time_start = time.time()
    FOLDERS = os.listdir( In_dir )
    for S1_FOLDER in FOLDERS:
        if len( S1_FOLDER ) == 72:
            Output_name = In_dir + S1_FOLDER[ :-4 ] + 'zip'
            if os.path.exists( Output_name ) == 0:
                f = zipfile.ZipFile( Output_name ,'w' ,zipfile.ZIP_DEFLATED )
                filelists = []      
                S1_dir = In_dir + S1_FOLDER
                dfs_get_zip_file( S1_dir, filelists )
                for file in filelists:
                    f.write(  file , arcname= S1_FOLDER + file[ 113: ] )
                f.close()
            print S1_FOLDER[ :-4 ] + 'have down'
    
    time_end = time.time()
    ZIP_Time = time_end - time_start
    print 'Classification Time:'
    print str( "%.*f" % (3, ZIP_Time / 60 ) ) + 'min' + str( "%.*f" % (3, ZIP_Time % 60 ) ) + 's'
    print "Well Down"
    
    
##Main
In_dir = r'G:\201606Sen\scihub.copernicus.eu\201611/'
Out_dir = In_dir
zip_path(In_dir, Out_dir)


Reference:
https://blog.csdn.net/wangtua/article/details/68943231

没有评论:

发表评论

LibSVM Chinese Brief Infroduction

Reference: [1]  https://blog.csdn.net/v_july_v/article/details/7624837 [2]  https://wenku.baidu.com/view/c402e983336c1eb91b375d37.html?fr...

  • Word (2)