rarfile

4.2 · active · verified Sat Apr 11

rarfile is a Python library for reading RAR archives, providing a `zipfile`-like interface. It acts as a wrapper around external utilities like `unrar`, `7zip`, `unar`, or `unrar-free`. The project is actively maintained with regular updates and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to open a RAR archive, list its contents, and shows commented-out examples for extracting files. It requires an external `unrar` binary (or similar) to be installed on your system and accessible via PATH for `rarfile` to function.

import rarfile
import os

# NOTE: This example requires an external 'unrar' (or 7zip/unar) binary
# to be installed and available in your system's PATH.
# Create a dummy rar file for demonstration (requires external tool)
# If you don't have one, replace 'example.rar' with an existing file.
# For a real scenario, you'd have an actual .rar file.

# Placeholder for a RAR file path
rar_file_path = 'example.rar'

# If you have an unrar tool, you could try creating a dummy rar file.
# For this example, we'll assume one exists or will be created externally.
# Example: os.system('rar a example.rar dummy_file.txt')
# This is out of scope for the quickstart, assuming the rar exists.

if not os.path.exists(rar_file_path):
    print(f"Warning: '{rar_file_path}' not found. Please create or provide an actual RAR file for this example.")
    print("Skipping quickstart execution due to missing RAR file.")
else:
    try:
        with rarfile.RarFile(rar_file_path, 'r') as rf:
            print(f"Contents of {rar_file_path}:")
            for info in rf.infolist():
                print(f"  - {info.filename} ({info.file_size} bytes)")

            # Example: Extract a specific file (if it exists)
            # file_to_extract = 'some_file_in_rar.txt'
            # if file_to_extract in rf.namelist():
            #     print(f"\nExtracting {file_to_extract}...")
            #     rf.extract(file_to_extract, path='./extracted_files')
            #     print(f"Extracted {file_to_extract} to ./extracted_files")

            # Example: Extract all files
            # print("\nExtracting all files...")
            # rf.extractall(path='./extracted_all')
            # print("All files extracted to ./extracted_all")

    except rarfile.RarFileError as e:
        print(f"Error opening RAR file: {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")

view raw JSON →