Advertisement
Guest User

Untitled

a guest
Apr 7th, 2020
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.67 KB | None | 0 0
  1. import os
  2. import io
  3. import zipfile
  4. import re
  5.  
  6.  
  7. def unzip_directory(directory):
  8.     """" This function unzips (and then deletes) all zip files in a
  9.    directory """
  10.     for root, dirs, files in os.walk(directory):
  11.         for filename in files:
  12.             if re.search(r'\.zip$', filename):
  13.                 to_path = os.path.join(root, filename.split('.zip')[0])
  14.                 zipped_file = os.path.join(root, filename)
  15.                 if not os.path.exists(to_path):
  16.                     os.makedirs(to_path)
  17.                     with zipfile.ZipFile(zipped_file, 'r') as zfile:
  18.                         zfile.extractall(path=to_path)
  19.                     # deletes zip file
  20.                     os.remove(zipped_file)
  21.  
  22.  
  23. def exists_zip(directory):
  24.     """ This function returns T/F whether any .zip file exists within the
  25.     directory, recursively """
  26.     is_zip = False
  27.     for root, dirs, files in os.walk(directory):
  28.         for filename in files:
  29.             if re.search(r'\.zip$', filename):
  30.                 is_zip = True
  31.     return is_zip
  32.  
  33.  
  34. def unzip_directory_recursively(directory, max_iter=1000):
  35.     print("Does the directory path exist? ", os.path.exists(directory))
  36.     """ Calls unzip_directory until all contained zip files (and new ones from
  37.    previous calls) are unzipped
  38.    """
  39.     iterate = 0
  40.     while exists_zip(directory) and iterate < max_iter:
  41.         unzip_directory(directory)
  42.         iterate += 1
  43.     pre = "Did not " if iterate < max_iter else "Did"
  44.     print(pre, "time out based on max_iter limit of", max_iter,
  45.           ". Took iterations:", iterate)
  46.  
  47.  
  48. file_path = r"X:\Poker\HH"
  49. unzip_directory_recursively(file_path)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement