10

I'm writing a Python script where I need to call 7z to extract some files kept inside a directory in an archive without extracting the complete archive. The archive contains multiple directories and I need to extract some files from a particular directory.

Let's say, "abc.7z" is an archive which contains multiple directories, i.e "temp", "windows", "system", "data". I want to extract some .exe files from directory "system" only because those .exe files might be present in other directories too but I am interested only in the files from "system".

All I need is the 7z command; I'll figure out how to call 7z from the script. Thanks for your help.

Matthias Braun
  • 32,039
  • 22
  • 142
  • 171
Anurag Tiwary
  • 123
  • 1
  • 1
  • 11

2 Answers2

27

You can specify a file/folder filter at the end of the command line. Check this for more details on 7zip command line commands and options.

7z.exe x [archive.7z] -o[output_dir] [filter]

e.g. 7z.exe x abc.7z -aoa -oC:\Temp system

You can also specify files of a particular type from system folder. For e.g. system\*.exe will extract all .exe files inside the system directory.

-aoa option is for overwrite mode.

To call it from Python you can use subprocess module. Something like:

import subprocess

cmd = []
cmd.append(r'C:\Program Files\7-Zip\7z.exe')
cmd.append('x')
cmd.append(archive)
cmd.append('-aoa')
cmd.append('-o{}'.format(dst_part))
cmd.append(file_folder_filter)
subprocess.call(cmd)
sk11
  • 1,779
  • 1
  • 17
  • 29
  • So it means that `7z.exe x abc.7z -aoa -oC:\Temp system\*.exe` will be the final command to extract only the .exe file from the system folder. – ρss Aug 13 '15 at 10:12
  • On my side, i need to add '.' before to make it works. That is to extract 'system' directory only i need to pass './system' – frachop Oct 19 '20 at 13:41
  • Note: you can use `e` instead of `x` if you want to get the files without the path they had inside the zip – Roman Feb 04 '21 at 06:43
  • Note for bash users regarding wildcards: use apostroph to not have bash trying to expand the wildcards. Like `7z e abc.7z "system/*.exe"` – Roman Feb 04 '21 at 06:52
5

Steps to extract a specific directory from 7z zip:

Specific Directory: rootdir/firstson/second

Zip file : test.7z

Command to use :

7z x test.7z rootdir/firstson/second
deadshot
  • 8,881
  • 4
  • 20
  • 39
Arun Murthy
  • 61
  • 1
  • 2