Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting all the files of a selected extension from a zipped file [closed]

Tags:

python

I am new to python, and I wanted to extract three single files of a different extensions each from a zipped file. I don't know their filenames, just their extensions.

Let's say that the following format exists:

---ZippedDirectory.zip

 |_
   RandomnameFile1.KnownFormat1
 |_
   RandomnameFile2.KnownFormat2
 |_
   RandomnameFile3.KnownFormat3
 |...

I need to extract the above files, I only know the formats. There might be other files in this zipped archive. I am confused as to how to achieve this, Any help would be awesome!

Thanks!

like image 717
BikerDude Avatar asked Jan 25 '26 16:01

BikerDude


2 Answers

you should be able to do something like this

import zipfile


def main():
    archive = 'archive.zip'
    directory = './'
    extensions = ('.txt', '.pdf')
    zip_file = zipfile.ZipFile(archive, 'r')
    [zip_file.extract(file, directory) for file in zip_file.namelist() if file.endswith(extensions)]
    zip_file.close()


if __name__ == '__main__':
    main()
like image 107
davidejones Avatar answered Jan 27 '26 06:01

davidejones


Mine is a simpler version of Jones'. Works for just one extension.

from zipfile import ZipFile

with ZipFile(r'C:\scratch\folder to process\try.zip') as theZip:
    fileNames = theZip.namelist()
    for fileName in fileNames:
        if fileName.endswith('py'):
            content = theZip.open(fileName).read()
            open(fileName, 'wb').write(content)
like image 29
Bill Bell Avatar answered Jan 27 '26 06:01

Bill Bell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!