libarchive-c Python Interface

5.3 · active · verified Thu Apr 16

libarchive-c is a Python interface to the C library libarchive, allowing users to read, write, and extract various archive formats like tar, zip, and 7z. It leverages `ctypes` for dynamic loading and is actively maintained, with regular releases (e.g., v5.3 released May 22, 2025). It is currently tested with Python 3.12 and 3.13.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple 'tar' archive with a file, and then extract its contents using the high-level `file_writer` and `extract_file` functions.

import libarchive
import os

# Create a dummy file
with open('test_file.txt', 'w') as f:
    f.write('Hello, libarchive-c!')

# Create an archive
archive_name = 'my_archive.tar'
with libarchive.file_writer(archive_name, 'tar') as archive:
    archive.add_files('test_file.txt')
print(f"Archive '{archive_name}' created.")

# Clean up the dummy file
os.remove('test_file.txt')

# Read and extract the archive
extracted_dir = 'extracted_content'
os.makedirs(extracted_dir, exist_ok=True)

os.chdir(extracted_dir)
libarchive.extract_file(os.path.join('..', archive_name)) # Extract from parent dir
os.chdir('..')

# Verify extraction
extracted_path = os.path.join(extracted_dir, 'test_file.txt')
if os.path.exists(extracted_path):
    with open(extracted_path, 'r') as f:
        content = f.read()
    print(f"Content extracted: {content}")
else:
    print("Extraction failed.")

# Clean up archive and extracted directory
os.remove(archive_name)
os.remove(extracted_path)
os.rmdir(extracted_dir)

view raw JSON →