Skip to content

Instantly share code, notes, and snippets.

@shreyanshvarshney
Last active May 18, 2020 16:02
Show Gist options
  • Save shreyanshvarshney/0f83c1bf76e1485418e7214995c45ccb to your computer and use it in GitHub Desktop.
Save shreyanshvarshney/0f83c1bf76e1485418e7214995c45ccb to your computer and use it in GitHub Desktop.
Python Script to automate directory compression.
import os
import subprocess as sp
print("What type of compression you want? \n0. Folders inside a Folder \n1. Direct Folder\n")
compression = input("Enter the number 0 or 1?\n")
# You may refer to the images mentioned in this blog, in the later section for better clarification.
if compression == '0':
path = input('Enter the Directory location in which you have to compress the inside folders/directories (Sample location: /Users/mymacname/Desktop/ParentDirectory) \n')
# Input your dicrectory path in which you have to compress the inside folders/directories.
dirs = [dir for dir in os.listdir(path) if os.path.isdir(os.path.join(path,dir))]
# Using List Comprehension for verifying the directories location you have given, exsits or not.
print(dirs)
# This prints your Directories which will be compressed, in this case they are named as 'DirectoryToBeCompressed1' and 'DirectoryToBeCompressed2' respectively.
for dir in dirs:
dir_path = path + '/' + dir
# This stores /Users/mymacname/Desktop/ParentDirectory/DirectoryToBeCompressed1 in dir_path in the first epoch.
dir_path_zip = dir_path + '.zip'
# This stores /Users/mymacname/Desktop/ParentDirectory/DirectoryToBeCompressed1.zip in dir_path_zip in the first epoch.
terminal = 'cd ' + path + '\n' + 'zip -r ' + dir_path_zip + ' ./' + dir
# This is the command which will run in the Terminal to initiate the process of Compression of Directories.
sp.run(terminal,shell=True)
#This will run a subprocess and that will result in your DirectoryToBeCompressed1.zip and DirectoryToBeCompressed2.zip containing the relative files you want.
print("yo!, you compressed the directories which are inside the given directory location successfully.")
elif compression == '1':
path = input('Enter the Directory location to be compressed (Sample location: /Users/mymacname/Desktop/ParentDirectory) \n')
# Input your dicrectory path here to be compressed
path_zip = path + '.zip'
# This stores /Users/mymacname/Desktop/ParentDirectory.zip in path_zip.
terminal = 'cd ' + path + '\n' + 'zip -r ' + path_zip + ' ./'
# This is the command which will run in the Terminal to initiate the process of Compression of Directories.
sp.run(terminal,shell=True)
print("yo!, you compressed the given directory successfully.")
else:
print("Oops! You entered invalid input. Try again.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment