Unzip many zip files to separate directories in Python

May 17, 2022 unzip python [code]

Code to unzip many zip files into their own separate directories.

#!/usr/bin/python3
import os

#List files
filenames = os.listdir()

for filename in filenames:
  #Look at files that end with .zip
  if filename.endswith('zip'):
    #Set dirname to first non-space chunk of zip file name
    dirname = filename.replace('.zip','').split()[0]
    os.system('mkdir ' + dirname)

    #Unzip into the dir created above.  Unzip takes the -d command for ouput directory.
    cmd = 'unzip -d ' + dirname + " '" + filename + "'"
    os.system(cmd)