Search code examples
pythonpermission-denied

Unzip some Files in a Folder


I have a problem with unzipping some zip files in a folder. I know how to do it with one zip file, but I don't know how to do it with 3 or more files in a folder.

I've tried this:

import zipfile
        
with zipfile.ZipFile('C:/Data/zipper/', 'r') as zip_ref:
    zip_ref.extractall('C:/Data/unzipped')

But here, I get this error:

elf.fp = io.open(file, filemode)
PermissionError: [Errno 13] Permission denied: 'C:/Data/unzipped/'

If I try this code with only one zip it works:

import zipfile
    
with zipfile.ZipFile("file.zip", "r") as zip_ref:
    zip_ref.extractall("targetdir")

Solution

  • It looks like the problem is that you're trying to open the directory ('C:/Data/zipper/') as a zip file.

    Try listing all the zip files in the directory and then looping through and unzipping them:

    import zipfile
    import os
    
    # Directory containing zip files
    zip_folder = 'C:/Data/zipper/'
    
    # Directory to extract files to
    extract_folder = 'C:/Data/unzipped/'
    
    # List all files in the zip folder
    files = os.listdir(zip_folder)
    
    # Loop through all files and check if it's a zip file
    for file in files:
        if file.endswith('.zip'):
            with zipfile.ZipFile(os.path.join(zip_folder, file), 'r') as zip_ref:
                zip_ref.extractall(extract_folder)
    

    Hope this helps.