I’m trying to extract multiple files from some .zip archives. My code is:
import os import zipfile os.chdir('/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos') for f in os.listdir("/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos"): if f.endswith(".zip"): z = zipfile.ZipFile(f, 'r') z.extractall(path = '/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos/dados') z.close()
However, it only extracts the files inside the first archive. I’m using Python 3.6. What is wrong?
Advertisement
Answer
I thought this scenario might be a serious candidate …
What happens is that for each .zip file, all its members are extracted, but they overwrite the ones extracted from the previous file (well, except the 1st). So, at the end, you end up with the files from the last archive that was enumerated.
To get past this issue, you should unzip each .zip file members in a separate directory (the .zip file name).
Below is an example (I also simplified / cleaned your code a bit).
code00.py:
#!/usr/bin/env python3 import os import glob import zipfile dir_name_base = r"/home/marlon/Shift One/Projeto Philips/Consolidação de Arquivos" for arc_name in glob.iglob(os.path.join(dir_name_base, "*.zip")): arc_dir_name = os.path.splitext(os.path.basename(arc_name))[0] zf = zipfile.ZipFile(arc_name) zf.extractall(path=os.path.join(dir_name_base, "dados", arc_dir_name)) zf.close() # Close file after extraction is completed