Search code examples
pythonzip

Using Python unable to unzip .mdf files only


Using Python trying to unzip .mdf files from multiple zip files in the same directory. The below code is not finding any .mdf files in the .zip files, because of how I have written it. It is looking at the .zip file not what is in them (I think). But I'm not sure how to amend it to get what I need. New to Python clearly.

import zipfile
import os

os.chdir(working_directory)

for file in os.listdir(working_directory):
    if zipfile.is_zipfile(file):
        with zipfile.ZipFile(file) as item:
            if file.endswith('.mdf'):
                item.extractall()

Solution

  • You are checking if file - which is the zip file - ends with .mdf or not. Which obviously won't work.

    You need to look inside the zip file. Once you have the zipfile open, you can call the namelist() method to get the list of names of the members of the zip file.

    import zipfile
    import os
    
    os.chdir(working_directory)
    
    for file in os.listdir(working_directory):
        if zipfile.is_zipfile(file):
            with zipfile.ZipFile(file) as item:
                for member in item.namelist():  # go through members of the zip file
                    if member.endswith('.mdf'):
                        item.extract(member)    # extract only the mdf file