Python 3.2+shutilfunction
shutil.unpack_archive()
archives
Unpacks a zip or tar archive into a directory; the format is guessed from the file name's extension.
Syntax
shutil.unpack_archive(filename, extract_dir=None, format=None, *, filter=None)
The format is decided by the name, not the contents: a file without a familiar extension raises shutil.ReadError even if it is a perfectly good zip — pass the format explicitly then. Without extract_dir it unpacks into the current directory. An untrusted archive is dangerous: tar can write outside the target directory; the filter parameter (3.12+, defaulting to 'data' since 3.14) limits that.
Examples
import os, shutil
os.mkdir('data')
open('data/a.txt', 'w').close()
name = shutil.make_archive('pack', 'gztar', root_dir='data')
shutil.unpack_archive(name, 'out', filter='data') # без filter 3.12–3.13 предупреждают
print(os.listdir('out')) # → ['a.txt']
import os, shutil
os.mkdir('data')
open('data/a.txt', 'w').close()
name = shutil.make_archive('pack', 'zip', root_dir='data')
os.rename(name, 'pack.bin')
try:
shutil.unpack_archive('pack.bin', 'out')
except shutil.ReadError as e:
print(e) # → Unknown archive format 'pack.bin'
shutil.unpack_archive('pack.bin', 'out', format='zip')
print(os.listdir('out')) # → ['a.txt']
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy