'Converting multiple zip files into regular folders
Can anyone help me to convert a lot of zip files at once using python?
I have "Years" folder which has 3 folders of "2019","2020" and "2021". Folder "2019" has folders of "1","2","3" folders. Folder "1" has "attachment.zip", Folder "2" has "attachment.zip" and Folder "3" has "attachment.zip. I want to go through each folder in order to convert all zip files and extract them to "Extracted" folder. Result should look like this:
Folder "1" has "attachment.zip" and folder of "Extracted".
Solution 1:[1]
Below is the code that worked for me:
import os, zipfile
dir_name = 'C:\\SomeDirectory'
extension = ".zip"
os.chdir(dir_name) # change directory from working dir to dir with files
for item in os.listdir(dir_name): # loop through items in dir
if item.endswith(extension): # check for ".zip" extension
file_name = os.path.abspath(item) # get full path of files
zip_ref = zipfile.ZipFile(file_name) # create zipfile object
zip_ref.extractall(dir_name) # extract file to dir
zip_ref.close() # close file
os.remove(file_name) # delete zipped file
Looking back at the code I had amended, the directory was getting confused with the directory of the script.
The following also works while not ruining the working directory. First remove the line
os.chdir(dir_name) # change directory from working dir to dir with files
Then assign
file_nameas
file_name = dir_name + "/" + item
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yxxhixx |
