It will create a zip archive ‘sampleDir2.zip’ with all csv files from given directory. ZipFilesInDir('sampleDir', 'sampleDir2.zip', lambda name : 'csv' in name) pass a lambda function as argument in it.
However, some tools (including older Python releases) do not support these compression methods, and may either refuse to process the ZIP file altogether, or fail to extract individual files. Let’s zip only csv files from a directory i.e. The ZIP file format specification has included support for bzip2 compression since 2001, and for LZMA compression since 2006. # create complete filepath of file in directory With ZipFile(zipFileName, 'w') as zipObj: # Zip the files from given directory that matches the filterĭef zipFilesInDir(dirName, zipFileName, filter): Files which pass the filter will only be added in zip i.e. Let’s create function that Iterates over a directory and filter the contents with given callback. To zip selected files from a directory we need to check the condition on each file path while iteration before adding it to zip file. SampleDir/logs/test_2.log 21:44:56 3552 Zip selected files from a directory based on filter or wildcards It will zip all the contents of a directory in to a single zip file i.e ‘sampleDir.zip’. ZipObj.write(filePath, basename(filePath)) #create complete filepath of file in directoryįilePath = os.path.join(folderName, filename) # Iterate over all the files in directoryįor folderName, subfolders, filenames in os.walk(dirName): With ZipFile('sampleDir.zip', 'w') as zipObj: To zip all the contents of a directory in a zip archive, we need to iterate over all the files in directory and it’s sub directories, then add each entry to the zip file using ZipFile.write() Checkout the detailed review.Įxplore a new career path with a 7 day free trial. Build data science skills, learn Python & SQL, analyze & visualize data, build machine learning models. Get a Professional Certificate in data Science by IBM. Looking for a Career in Data Science or Machine Learning with Python? With ZipFile('sample2.zip', 'w') as zipObj2: It will automatically close the zip file when ZipFile object goes out of scope i.e.
We can do the same thing with “with open”. It will create a zip file ‘sample.zip’ with given files inside it.
Let’s use this to create a zip archive file.įrom zipfile import ZipFile Create a zip archive from multiple files in Python
Python’s zipfile module provides a ZipFile class for zip file related stuff.
In this article we will discuss how to create a zip archive from selected files or files from a directory based on filters.