Python read rar file

rarfile — Work with RAR archives¶

The RAR file format is a common archive and compression standard. This module provides tools to read and list a RAR file.

This module is based on the UnRAR library (provided by RARLAB) through a ctypes wrapper, and inspired on Python’s ZipFile.

The module defines the following items:

exception rarfile. BadRarFile ¶

The error raised for bad RAR files.

The class for reading RAR files. See section RarFile Objects for constructor details.

Class used to represent information about a member of an archive. Instances of this class are returned by the getinfo() and infolist() methods of RarFile objects. Most users of the rarfile module will not need to create these, but only use those created by this module. header should be a RARHeaderDataEx instance as returned by unrarlib ; the fields are described in section RarInfo Objects .

rarfile. is_rarfile ( filename ) ¶

Returns True if filename is a valid RAR file based on its magic number, otherwise returns False .

RARLAB Official RAR site. RAR addons RAR addons where you can download UnRAR library sources.

RarFile Objects¶

Open a RAR file, where file should be a path to a file (a string). The mode parameter should be ‘r’ to read an existing file (only allowed mode at the moment).

Return a RarInfo object with information about the archive member name. Calling getinfo() for a name not currently contained in the archive will raise a KeyError .

Return a list containing a RarInfo object for each member of the archive. The objects are in the same order as their entries in the actual RAR file on disk if an existing archive was opened.

Return a list of archive members by name.

RarFile. open ( member [ , pwd ] ) ¶

Extract a member from the archive as a file-like object (see Python’s io.BytesIO ). member is the name of the file in the archive, or a RarInfo object. pwd is the password used for encrypted files.

Return the bytes of the file member in the archive. member is the name of the file in the archive, or a RarInfo object. pwd is the password used for encrypted files and, if specified, it will override the default password set with setpassword() .

Extract a member from the archive to the current working directory; member must be its full name or a RarInfo object). Its file information is extracted as accurately as possible. path specifies a different directory to extract to. member can be a filename or a RarInfo object. pwd is the password used for encrypted files.

RarFile. extractall ( path=None, members=None, pwd=None ) ¶

Extract all members from the archive to the current working directory. path specifies a different directory to extract to. members is optional and must be a subset of the list returned by namelist() . pwd is the password used for encrypted files.

Never extract archives from untrusted sources without prior inspection. It is possible that files are created outside of path, e.g. members that have absolute filenames starting with «/» or filenames with two dots «..» .

Print a table of contents for the archive to sys.stdout .

Set pwd as default password to extract encrypted files.

Read all the files in the archive and check their CRC’s and file headers. Return the name of the first bad file, or else return None .

The following data attribute is also available:

The comment text associated with the RAR file, if any.

RarInfo Objects¶

Instances of the RarInfo class are returned by the getinfo() and infolist() methods of RarFile objects. Each object stores information about a single member of the RAR archive.

Instances have the following attributes:

Name of the file in the archive.

The time and date of the last modification to the archive member. This is a tuple of six values:

Index Value
0 Year (>= 1980)
1 Month (one-based)
2 Day of month (one-based)
3 Hours (zero-based)
4 Minutes (zero-based)
5 Seconds (zero-based)

The RAR file format does not support timestamps before 1980.

Type of compression for the archive member.

Comment for the individual archive member.

System which created RAR archive.

RAR version needed to extract archive.

CRC-32 of the uncompressed file.

Size of the compressed data.

Size of the uncompressed file.

© Copyright 2012, Matias Bordese. Revision b1ac46cb .

Versions latest stable v0.3 v0.2 Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

rarfile API documentation¶

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

  • 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.
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. RarFile ( file, mode=’r’, charset=None, info_callback=None, crc_check=True, errors=’stop’, part_only=False ) ¶

Parse RAR structure, provide access to files in archive.

Archive comment. Unicode string or None.

File name, if available. Unicode string or None.

Sets the password to use when extracting.

Returns True if any archive entries require password for extraction.

Return list of filenames in archive.

Return RarInfo objects for all files/directories in archive.

Returns filenames of archive volumes.

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

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.

Return uncompressed data for archive entry.

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

Print archive file list to stdout or given file.

Extract single file into current directory.

Extract all files into current directory.

Read all files and test CRC.

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

RarInfo class¶

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

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

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

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

Compression method: one of RAR_M0 .. RAR_M5 constants.

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

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

Host OS type, one of RAR_OS_* constants.

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

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

Optional time field: creation time. As datetime object.

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

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

CRC-32 of uncompressed file, unsigned int.

Blake2SP hash over decompressed data. (RAR5-only)

Volume nr, starting from 0.

Volume file name, where file starts.

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

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.

Returns True if entry is a directory.

Returns True if entry is a symlink.

Returns True if entry is a normal file.

Returns True if data is stored password-protected.

Returns True if entry is a directory.

Deprecated since version 4.0.

RarExtFile class¶

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

Provides public methods and common crc checking.

  • no short reads — .read() and .readinfo() read as much as requested.
  • no internal buffer, use io.BufferedReader for that.

Filename of the archive entry

Read all or specified amount of data from archive entry.

Zero-copy read directly into buffer.

Return current reading position in uncompressed data.

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

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

Returns underlying file descriptor if one exists.

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

Return whether this is an ‘interactive’ stream.

Return False if it can’t be determined.

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.

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.

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¶

Datetime that carries nanoseconds.

Arithmetic not supported, will lose nanoseconds.

Formats with nanosecond precision by default.

replace ( year=None, month=None, day=None, hour=None, minute=None, second=None, microsecond=None, tzinfo=None, *, fold=None, nanosecond=None ) ¶

Return new timestamp with specified fields replaced.

Functions¶

Check quickly whether file is rar archive.

rarfile. is_rarfile_sfx ( xfile ) ¶

Check whether file is rar archive with support for SFX.

It will read 2M from file.

Constants¶

Compression level -m1 — Fastest compression.

Compression level -m5 — Maximum compression.

Warnings¶

Archive uses feature that are unsupported by rarfile.

Exceptions¶

Base class for rarfile errors.

Incorrect data in archive.

The file is not RAR archive.

Cannot guess multipart name components.

class rarfile. PasswordRequired ¶

class rarfile. NeedFirstVolume ( msg, volume ) ¶

Need to start from first volume.

Volume number of current file or None if not known

Cannot parse encrypted headers — no crypto available.

class rarfile. RarExecError ¶

Problem reported by unrar/rar.

class rarfile. RarFatalError ¶

class rarfile. RarCRCError ¶

CRC error during unpacking

class rarfile. RarLockedArchiveError ¶

Must not modify locked archive

class rarfile. RarWriteError ¶

class rarfile. RarOpenError ¶

class rarfile. RarUserError ¶

class rarfile. RarMemoryError ¶

class rarfile. RarCreateError ¶

class rarfile. RarNoFilesError ¶

No files that match pattern were found

class rarfile. RarUserBreak ¶

class rarfile. RarWrongPassword ¶

class rarfile. RarUnknownError ¶

class rarfile. RarSignalExit ¶

class rarfile. RarCannotExec ¶

Источник

Python read rar file

Learn Latest Tutorials

Splunk tutorial

SPSS tutorial

Swagger tutorial

T-SQL tutorial

Tumblr tutorial

React tutorial

Regex tutorial

Reinforcement learning tutorial

R Programming tutorial

RxJS tutorial

React Native tutorial

Python Design Patterns

Python Pillow tutorial

Python Turtle tutorial

Keras tutorial

Preparation

Aptitude

Logical Reasoning

Verbal Ability

Company Interview Questions

Artificial Intelligence

AWS Tutorial

Selenium tutorial

Cloud Computing

Hadoop tutorial

ReactJS Tutorial

Data Science Tutorial

Angular 7 Tutorial

Blockchain Tutorial

Git Tutorial

Machine Learning Tutorial

DevOps Tutorial

B.Tech / MCA

DBMS tutorial

Data Structures tutorial

DAA tutorial

Operating System

Computer Network tutorial

Compiler Design tutorial

Computer Organization and Architecture

Discrete Mathematics Tutorial

Ethical Hacking

Computer Graphics Tutorial

Software Engineering

html tutorial

Cyber Security tutorial

Automata Tutorial

C Language tutorial

C++ tutorial

Java tutorial

.Net Framework tutorial

Python tutorial

List of Programs

Control Systems tutorial

Data Mining Tutorial

Data Warehouse Tutorial

Javatpoint Services

JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.

  • Website Designing
  • Website Development
  • Java Development
  • PHP Development
  • WordPress
  • Graphic Designing
  • Logo
  • Digital Marketing
  • On Page and Off Page SEO
  • PPC
  • Content Development
  • Corporate Training
  • Classroom and Online Training
  • Data Entry

Training For College Campus

JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week

Like/Subscribe us for latest updates or newsletter RSS Feed Subscribe to Get Email Alerts Facebook Page Twitter Page YouTube Blog Page

Источник

Читайте также:  Сброс строки в html
Оцените статью