I have a zip file with internal folder structure as:
CODE
`-- CODE
`-- CODE
`-- CODE
|-- 2019
| |-- file1.txt
| `-- file2.txt
|-- 2020
| `-- file3.txt
`-- 2021
|-- file4.txt
`-- file5.txt
And I want to unzip the files in folder structure as given below:
CODE
|-- 2019
| |-- file1.txt
| `-- file2.txt
|-- 2020
| `-- file3.txt
`-- 2021
|-- file4.txt
`-- file5.txt
I could hard code it, however, since it is a repeating request, can I programmatically handle this to unzip only folders which have files in them.
My current code is:
def unzipfiles(incoming_path):
for path,subdirs,files in os.walk(incoming_path):
for name in files:
if(name.endswith('.zip')):
with zipfile.ZipFile(os.path.join(incoming_path,name), 'r') as zip_ref:
for file in zip_ref.namelist():
out_path=os.path.join(incoming_path,file)
out_path=out_path.replace('CODE/','')
if(out_path[:-1]!=incoming_path):
zip_ref.extract(file,out_path)
However, it is not working correctly, and creating more folders than present in zip file.