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!
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()
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With