-1

I would like to extract multiple .7z files using Python. I've tried this, but it only extracted one file. I already put in a loop.

Below is what I've tried.

import os.path
import glob
from pyunpack import Archive

os.chdir("E:/DATA/raw")
for file in glob.glob("*myfile.7z"):
    print(file)
    Archive(file).extractall("E:/DATA/output")

The names of the 7z files are:

AHFWHSH_1438923_myfile.7z
KFWFAUF_3257485_myfile.7z
GDSHUHG_8975498_myfile.7z

My expected output folders are:

output1
output2
output3
LeopardShark
  • 3,820
  • 2
  • 19
  • 33
Cheries
  • 834
  • 1
  • 13
  • 32

1 Answers1

2

If your expected output is output1, output2, output3, then you should add the index to the output path. You should also create the directories before extracting the files, by using os.mkdir():

import os
import glob
from pyunpack import Archive

for i, f in enumerate(glob.glob(os.path.join("E:/DATA/raw", "*myfile.7z"))):
    dir_path = "E:/DATA/output" + str(i+1)
    os.mkdir(dir_path)
    Archive(f).extractall(dir_path)
Vito Gentile
  • 13,336
  • 9
  • 61
  • 96
  • Hi @Vito, thank you for your answer. But I got an error: `ValueError: directory does not exist:E:/DATA/output1` – Cheries Nov 18 '21 at 10:04
  • I've updated the answer by adding the creation of the output directories, right before extracting the files – Vito Gentile Nov 18 '21 at 10:56
  • Hi, thank you so much, it works. But I found that one of the result in the output3 missing 1 folder after extracting. – Cheries Nov 19 '21 at 03:23