The Python code below will create a zip file from the files and any subdirectories within a specified directory. I.e., it will recursively compress the files within a directory.
#!/usr/bin/python # Name: zipdir.py # Version: 1.0 # Created: 2016-11-13 # Last modified: 2016-11-13 # Purpose: Creates a zip file given a directory where the files to be zipped # are stored and the name of the output file. Don't include the .zip extension # when specifying the zip file name. # Usage: zipdir.py output_filename dir_name # Note: if the output file name and directory are not specified on the # command line, the script will prompt for them. import sys, shutil if len(sys.argv) == 1: dir_name = raw_input("Directory name: ") output_filename = raw_input("Zip file name: ") elif len(sys.argv) == 3: output_filename = sys.argv[1] dir_name = sys.argv[2] else: print "Incorrect number of arguments! Usage: zipdir.py output_filename dir_name" exit() shutil.make_archive(output_filename, 'zip', dir_name)
The script takes two
arguments: the output file name and the directory to be
compressed. The .zip extension should not be included with the output
file name; it will automatically be appended to the output file name. If
no arguments are specified on the command line, the script will prompt for
them. E.g., if I wanted to create a zip file named test.zip from
the contents of the folder Example, I could use the command
python zipdir.py test Example
or, if the zipdir.py
script is
made executable on a
Linux or
Apple OS X system with
chmod u+x zipdir.py
, then ./zipdir.py test Example
can be used.