Wednesday, August 5, 2009

Python - Drag and Drop Zip

I often need to quickly zip a folder or file on my desktop to email off to someone. I have 7-zip installed, and it is a great program, but wanted to come up with something even easier to use as well as try something new.

I created a Python script that sits on my desktop called "Zip". To create a zip archive of a file or folder, I simply drag and drop the file onto the "Zip" script and a new .zip file will show up wherever the script is located. It works just fine, and does not require any non-standard Python modules. Tested on on Windows, Python 2.6.2.

Here is the script source:


import os, sys
import zipfile

# Make sure a folder or directory was specified
if len(sys.argv) == 1:
sys.exit(1)

# Assign name of file or folder to resusable variable
resource = sys.argv[1]

# Create name of new zip file, based on original folder or file name
zipFileName = os.path.splitext(resource)[0] + '.zip'

# Create zip file
zipFile = zipfile.ZipFile(zipFileName, "w")

# Function to create the archive name
# Otherwise the zip folder contains many, unnecessary sub folders
def getArchiveName(resource, root, file):
if root == resource:
return (os.sep).join([resource, file])
else:
return (os.sep).join([resource, root, file])

# Write file(s) to the zipFile
print "Creating zip archive..."
if os.path.isdir(resource):
for root, dirs, files in os.walk(resource):
for file in files:
zipFile.write((os.sep).join([root, file]),
getArchiveName(os.path.basename(resource), os.path.basename(root), file),
zipfile.ZIP_DEFLATED)
else:
zipFile.write(resource, os.path.basename(resource), zipfile.ZIP_DEFLATED)

# Close file when finished
zipFile.close()

You can also download the script here: Zip.py

The unzip version is coming soon.
blog comments powered by Disqus