rarfile API

Introduction

RAR archive reader.

This is Python module for Rar archive reading. The interface is made as zipfile-like as possible.

Basic logic:
  • Parse archive structure with Python.

  • Extract non-compressed files with Python

  • Extract compressed files with unrar.

  • Optionally write compressed data to temp file to speed up unrar, otherwise it needs to scan whole archive on each execution.

Example:

import rarfile

rf = rarfile.RarFile("myarchive.rar")
for f in rf.infolist():
    print(f.filename, f.file_size)
    if f.filename == "README":
        print(rf.read(f))

Archive files can also be accessed via file-like object returned by RarFile.open():

import rarfile

with rarfile.RarFile("archive.rar") as rf:
    with rf.open("README") as f:
        for ln in f:
            print(ln.strip())

For decompression to work, either unrar or unar tool must be in PATH.

RarFile class

class RarFile(file: str | Path | FileLike, mode: str = 'r', charset: str | None = None, info_callback: Callable[[RarEntry], None] | None = None, crc_check: bool = True, errors: Literal['stop', 'strict'] = 'stop', part_only: bool = False)

Parse RAR structure, provide access to files in archive.

Parameters:
  • file -- archive file name or file-like object.

  • mode -- only "r" is supported.

  • charset -- fallback charset to use, if filenames are not already Unicode-enabled.

  • info_callback -- debug callback, gets to see all archive entries.

  • crc_check -- set to False to disable CRC checks

  • errors -- Either "stop" to quietly stop parsing on errors, or "strict" to raise errors. Default is "stop".

  • part_only --

    If True, read only single file and allow it to be middle-part of multi-volume archive.

    Added in version 4.0.

comment: str | None = None

Archive comment. Unicode string or None.

filename: str | None = None

File name, if available. Unicode string or None.

__enter__() RarFile

Open context.

__exit__(typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None) None

Exit context.

__iter__() Iterator[RarInfo]

Iterate over members.

setpassword(pwd: str | None) None

Sets the password to use when extracting.

needs_password() bool

Returns True if any archive entries require password for extraction.

is_solid() bool

Returns True if archive uses solid compression.

Added in version 4.2.

namelist() list[str]

Return list of filenames in archive.

infolist() Sequence[RarInfo]

Return RarInfo objects for all files/directories in archive.

volumelist() Sequence[str | bytes | Path | FileLike]

Returns filenames of archive volumes.

In case of single-volume archive, the list contains just the name of main archive file.

getinfo(name: str | Path | RarInfo) RarInfo

Return RarInfo for file.

getinfo_orig(name: str | Path | RarInfo) RarInfo

Return RarInfo for file source.

RAR5: if name is hard-linked or copied file, returns original entry with original filename.

Added in version 4.1.

open(name: str | Path | RarInfo, mode: str = 'r', pwd: str | None = None) RarExtFile

Returns file-like object (RarExtFile) from where the data can be read.

The object implements io.RawIOBase interface, so it can be further wrapped with io.BufferedReader and io.TextIOWrapper.

On older Python where io module is not available, it implements only .read(), .seek(), .tell() and .close() methods.

The object is seekable, although the seeking is fast only on uncompressed files, on compressed files the seeking is implemented by reading ahead and/or restarting the decompression.

Parameters:
  • name -- file name or RarInfo instance.

  • mode -- must be "r"

  • pwd -- password to use for extracting.

read(name: str | Path | RarInfo, pwd: str | None = None) bytes

Return uncompressed data for archive entry.

For longer files using open() may be better idea.

Parameters:
  • name -- filename or RarInfo instance

  • pwd -- password to use for extracting.

close() None

Release open resources.

printdir(file: IO[str] | None = None) None

Print archive file list to stdout or given file.

extract(member: str | Path | RarInfo, path: str | Path | None = None, pwd: str | None = None) str | None

Extract single file into current directory.

Parameters:
  • member -- filename or RarInfo instance

  • path -- optional destination path

  • pwd -- optional password to use

extractall(path: str | Path | None = None, members: Iterable[str | Path | RarInfo] | None = None, pwd: str | None = None) None

Extract all files into current directory.

Parameters:
  • path -- optional destination path

  • members -- optional filename or RarInfo instance list to extract

  • pwd -- optional password to use

testrar(pwd: str | None = None) None

Read all files and test CRC.

strerror() str | None

Return error string if parsing failed or None if no problems.

RarInfo class

class RarInfo

Bases: RarEntry

A file entry in rar archive.

Timestamps as datetime are without timezone in RAR3, with UTC timezone in RAR5 archives.

filename

File name with relative path. Path separator is "/". Always unicode string.

Type:

str

date_time

File modification timestamp. As tuple of (year, month, day, hour, minute, second). RAR5 allows archives where it is missing, it's None then.

Type:

tuple[int, int, int, int, int, int] | None

comment

Optional file comment field. Unicode string. (RAR3-only)

Type:

str | None

file_size

Uncompressed size.

Type:

int

compress_size

Compressed size.

Type:

int | None

compress_type

Compression method: one of RAR_M0 .. RAR_M5 constants.

Type:

int

extract_version

Minimal Rar version needed for decompressing. As (major*10 + minor), so 2.9 is 29.

RAR3: 10, 20, 29

RAR5 does not have such field in archive, it's simply set to 50.

Type:

int

host_os

Host OS type, one of RAR_OS_* constants.

RAR3: RAR_OS_WIN32, RAR_OS_UNIX, RAR_OS_MSDOS, RAR_OS_OS2, RAR_OS_BEOS.

RAR5: RAR_OS_WIN32, RAR_OS_UNIX.

Type:

int

mode

File attributes. May be either dos-style or unix-style, depending on host_os.

Type:

int

mtime

File modification time. Same value as date_time but as datetime object with extended precision.

Type:

datetime.datetime | None

ctime

Optional time field: creation time. As datetime object.

Type:

datetime.datetime | None

atime

Optional time field: last access time. As datetime object.

Type:

datetime.datetime | None

arctime

Optional time field: archival time. As datetime object. (RAR3-only)

Type:

datetime.datetime | None

CRC

CRC-32 of uncompressed file, unsigned int.

RAR5: may be None.

Type:

int | None

blake2sp_hash

Blake2SP hash over decompressed data. (RAR5-only)

Type:

bytes | None

volume

Volume nr, starting from 0.

Type:

int

volume_file

Volume file name, where file starts.

Type:

str | bytes | pathlib.Path | rarfile.utils.FileLike | None

file_redir

If not None, file is link of some sort. Contains tuple of (type, flags, target). (RAR5-only)

Type is one of constants:

RAR5_XREDIR_UNIX_SYMLINK

Unix symlink.

RAR5_XREDIR_WINDOWS_SYMLINK

Windows symlink.

RAR5_XREDIR_WINDOWS_JUNCTION

Windows junction.

RAR5_XREDIR_HARD_LINK

Hard link to target.

RAR5_XREDIR_FILE_COPY

Current file is copy of another archive entry.

Flags may contain bits:

RAR5_XREDIR_ISDIR

Symlink points to directory.

Type:

tuple[int, int, str] | None

is_dir() bool

Returns True if entry is a directory.

Added in version 4.0.

Returns True if entry is a symlink.

Added in version 4.0.

is_file() bool

Returns True if entry is a normal file.

Added in version 4.0.

isdir() bool

Returns True if entry is a directory.

Deprecated since version 4.0.

RarEntry class

class RarEntry

Base class for all records in a rar archive.

Added in version 5.0.

type

RAR3 block type. One of RAR_BLOCK_* constants. RAR5 blocks are mappend

Type:

int

flags

File modification timestamp. As tuple of (year, month, day, hour, minute, second). RAR5 allows archives where it is missing, it's None then.

Type:

int

block_type

RAR5 block type. One of RAR5_BLOCK_* contants. None on RAR3.

Type:

int | None

needs_password() bool

Returns True if data is stored password-protected.

RarExtFile class

class RarExtFile

Bases: RawIOBase

Base class for file-like object that RarFile.open() returns.

Provides public methods and common crc checking.

Behaviour:
  • no short reads - .read() and .readinfo() read as much as requested.

  • no internal buffer, use io.BufferedReader for that.

name: str | None = None

Filename of the archive entry

read(n: int | None = -1) bytes

Read all or specified amount of data from archive entry.

close() None

Close open resources.

readinto(buf: bytearray | memoryview | Buffer) int

Zero-copy read directly into buffer.

Returns bytes read.

tell() int

Return current reading position in uncompressed data.

seek(offset: int, whence: int = 0) int

Seek in data.

On uncompressed files, the seeking works by actual seeks so it's fast. On compressed files its slow - forward seeking happens by reading ahead, backwards by re-opening and decompressing from the start.

readable() bool

Returns True

writable() bool

Returns False.

Writing is not supported.

seekable() bool

Returns True.

Seeking is supported, although it's slow on compressed files.

readall() bytes

Read all remaining data

fileno()

Return underlying file descriptor if one exists.

Raise OSError if the IO object does not use a file descriptor.

isatty()

Return whether this is an 'interactive' stream.

Return False if it can't be determined.

readline(size=-1, /)

Read and return a line from the stream.

If size is specified, at most size bytes will be read.

The line terminator is always b'n' for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.

readlines(hint=-1, /)

Return a list of lines from the stream.

hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

writelines(lines, /)

Write a list of lines to stream.

Line separators are not added, so it is usual for each of the lines provided to have a line separator at the end.

nsdatetime class

class nsdatetime(..., nanosecond=0)

Bases: datetime

Datetime that carries nanoseconds.

Arithmetic operations will lose nanoseconds.

Added in version 4.0.

nanosecond: int

Number of nanoseconds, 0 <= nanosecond <= 999999999

astimezone(tz: tzinfo | None = None) nsdatetime

Convert to new timezone.

isoformat(sep: str = 'T', timespec: str = 'auto') str

Formats with nanosecond precision by default.

replace(..., nanosecond=0)

Return new timestamp with specified fields replaced.

Functions

is_rarfile(xfile: str | bytes | Path | FileLike) bool

Check quickly whether file is rar archive.

is_rarfile_sfx(xfile: str | bytes | Path | FileLike) bool

Check whether file is rar archive with support for SFX.

It will read 2M from file.

Constants

RAR constants

RAR_BLOCK_MARK: Final = 114

Archive signature

RAR_BLOCK_MAIN: Final = 115

Archive header

RAR_BLOCK_FILE: Final = 116

File entry

RAR_BLOCK_OLD_COMMENT: Final = 117

RAR2 archive comment

RAR_BLOCK_OLD_EXTRA: Final = 118

RAR2 verification

RAR_BLOCK_OLD_SUB: Final = 119

RAR2 file metadata

RAR_BLOCK_OLD_RECOVERY: Final = 120

RAR2 recovery

RAR_BLOCK_OLD_AUTH: Final = 121

RAR2 authenticity

RAR_BLOCK_SUB: Final = 122

RAR3 named subblock

RAR_BLOCK_ENDARC: Final = 123

End of archive

RAR_OS_MSDOS: Final = 0

MSDOS (only in RAR3)

RAR_OS_OS2: Final = 1

OS2 (only in RAR3)

RAR_OS_WIN32: Final = 2

Windows

RAR_OS_UNIX: Final = 3

UNIX

RAR_OS_MACOS: Final = 4

MacOS (only in RAR3)

RAR_OS_BEOS: Final = 5

BeOS (only in RAR3)

RAR_M0: Final = 48

No compression.

RAR_M1: Final = 49

Compression level -m1 - Fastest compression.

RAR_M2: Final = 50

Compression level -m2.

RAR_M3: Final = 51

Compression level -m3.

RAR_M4: Final = 52

Compression level -m4.

RAR_M5: Final = 53

Compression level -m5 - Maximum compression.

RAR5_BLOCK_MAIN: Final = 1

Archive header

RAR5_BLOCK_FILE: Final = 2

File entry

RAR5_BLOCK_SERVICE: Final = 3

Non-file entry

RAR5_BLOCK_ENCRYPTION: Final = 4

Header encryption parameters

RAR5_BLOCK_ENDARC: Final = 5

Archive end

Warnings

class UnsupportedWarning

Archive uses feature that are unsupported by rarfile.

Added in version 4.0.

Exceptions

class Error

Base class for rarfile errors.

class BadRarFile

Incorrect data in archive.

class NotRarFile

The file is not RAR archive.

class BadRarName

Cannot guess multipart name components.

class NoRarEntry

File not found in RAR

class PasswordRequired

File requires password

class BadSymLinkError

Invalid symbolic link

class NeedFirstVolume(msg: str, volume: int | None)

Need to start from first volume.

current_volume

Volume number of current file or None if not known

class NoCrypto

Cannot parse encrypted headers - no crypto available.

class RarExecError

Problem reported by unrar/rar.

class RarWarning

Non-fatal error

class RarFatalError

Fatal error

class RarCRCError

CRC error during unpacking

class RarLockedArchiveError

Must not modify locked archive

class RarWriteError

Write error

class RarOpenError

Open error

class RarUserError

User error

class RarMemoryError

Memory error

class RarCreateError

Create error

class RarNoFilesError

No files that match pattern were found

class RarUserBreak

User stop

class RarWrongPassword

Incorrect password

class RarUnknownError

Unknown exit code

class RarSignalExit

Unrar exited with signal

class RarCannotExec

Executable not found.

Types

type DateTuple = tuple[int, int, int, int, int, int]

Type for date components.

type PathLike = str | bytes | Path

Type for file names.

class FileLike

Bases: Protocol

read(size: int = -1, /) bytes
seek(ofs: int, whence: int = 0, /) int
tell() int
close() None
class RawFileLike

Bases: Protocol

read(size: int = -1, /) bytes
readinto(buf: bytearray | memoryview | Buffer, /) int
seek(ofs: int, whence: int = 0, /) int
tell() int
close() None