How to Extract Specific File Types From Zip Files With Python Programming
- 1). Import the zipfile module using the command "import zipfile."
- 2). Open a text editor such as Notepad or a code editor such as jEdit or Komodo Edit. Create a new file and save it with the extension .py. In the file, assign the path of the zip file to a variable by typing the following, replacing "zip_file.zip" with the name of your zip file.
fullpathToZip = "c:\\temp\\zip_file.zip" - 3). Assign the destination path to a variable by typing the following.
destinationPath = "c:\\temp\\Extracted" - 4). Open the zip file as read only and assign the resulting object to a variable by typing the following.
sourceZip = zipfile.ZipFile(fullpathToZip, 'r') - 5). Iterate through the list of file names archived within the zip file by using a for loop by typing the following.
for name in sourceZip.namelist(): - 6). Inspect each file name within the zip archive for the file extension you are seeking with each iteration of the for loop, remembering to indent a little to stay inside the for loop. For example, if you want only .txt files to be extracted, type the following.
if name.find('.txt')!= -1 - 7). Extract each file of your desired file type to the folder you have specified. Remember to indent a little to stay inside the if block thats inside the for loop. Type the following.
sourceZip.extract(name, destinationPath) - 8). Close your zipfile object. Keep in mind that you don't want the zipfile object to be closed until the for loop has finished iterating through each file name. Lined up this line with the beginning of the for loop line. For example, type
sourceZip.close()
Source...