Python Glossary Русский

Python 3.2+shutilfunction

shutil.register_unpack_format()

archives

Registers a custom format for unpack_archive(): a name, a list of extensions and an unpacking function.

Syntax

shutil.register_unpack_format(name, extensions, function, extra_args=None, description='')

The function is called as function(filename, extract_dir, **kwargs). An extension already taken by another format is not overridden: registration fails with shutil.RegistryError, so you cannot hijack '.zip' — unregister_unpack_format first. This is the opposite of register_archive_format, which replaces a format silently.

Examples

import os, shutil
def unpack_lst(filename, extract_dir, **kwargs):
    os.makedirs(extract_dir, exist_ok=True)
    for line in open(filename).read().split():
        open(os.path.join(extract_dir, line), 'w').close()
shutil.register_unpack_format('lst', ['.lst'], unpack_lst)
with open('files.lst', 'w') as f:
    f.write('a.txt b.txt')
shutil.unpack_archive('files.lst', 'out')
print(sorted(os.listdir('out')))  # → ['a.txt', 'b.txt']
import shutil
try:
    shutil.register_unpack_format('myzip', ['.zip'], lambda f, d: None)
except shutil.RegistryError as e:
    print(e)  # → .zip is already registered for "zip"

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy