Skip to content

Instantly share code, notes, and snippets.

@santiago-salas-v
Forked from kalkulus/unzip_all.py
Last active December 25, 2022 23:34
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save santiago-salas-v/3778ef0c95994cde0930ab3c25102e8a to your computer and use it in GitHub Desktop.
Save santiago-salas-v/3778ef0c95994cde0930ab3c25102e8a to your computer and use it in GitHub Desktop.
PYTHON: unzip / unrar all files in a directory at same directory where rar file present. Remove original archive.
#!/usr/bin/python
import os, zipfile, pyunpack
basis_folder = r'C:\Users\ssv\Documents\tmp'
for root, dirs, files in os.walk(basis_folder):
for filename in files:
if filename.endswith(".rar") :
print('RAR:'+os.path.join(root,filename))
elif filename.endswith(".zip"):
print('ZIP:'+os.path.join(root,filename))
name = os.path.splitext(os.path.basename(filename))[0]
if filename.endswith(".rar") or filename.endswith(".zip"):
try:
arch = pyunpack.Archive(os.path.join(root,filename))
# os.mkdir(name)
arch.extractall(directory=root)
os.remove(os.path.join(root,filename))
except Exception as e:
print("ERROR: BAD ARCHIVE "+os.path.join(root,filename))
print(e)
try:
# os.path.join(root,filename)os.remove(filename)
pass
except OSError as e: # this would be "except OSError, e:" before Python 2.6
if e.errno != errno.ENOENT: # errno.ENOENT = no such file or directory
raise # re-raise exception if a different error occured
@WarrenJD
Copy link

WarrenJD commented Feb 2, 2021

Thank you for the code, but when using a rare with multiple parts it only removes the first file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment