Python create rar archive

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 РАБОТА С АРХИВАМИ RAR

Python предоставляет обширный функционал по работе с архивами, включая RAR-формат. Основная библиотека для работы с архивами — zipfile, однако она не поддерживает RAR. Для этих целей можно использовать rarfile.

Для начала необходимо установить библиотеку rarfile при помощи pip:

После установки можно создавать, распаковывать и добавлять файлы в архивы RAR. Например, чтобы создать новый архив, необходимо использовать следующий код:

import rarfile
rf = rarfile.RarFile(‘example.rar’, mode=’w’)
rf.write(‘file.txt’)
rf.close()

В этом примере мы импортировали библиотеку rarfile, создали новый объект RarFile(), указав имя архива и режим записи (‘w’), добавили в архив файл file.txt при помощи метода write() и закрыли архив методом close().

Чтобы извлечь файлы из архива, нужно использовать режим чтения (‘r’) и соответствующие методы:

rf = rarfile.RarFile(‘example.rar’, mode=’r’)
rf.extractall()
rf.close()

В этом примере мы открыли архив в режиме чтения, извлекли все файлы методом extractall() и закрыли архив методом close().

Архивация данных — Библиотеки программ Python — zipfile — Записки программиста

Scrape Reddit like a PRO with Python

Работа с zip-архивами на python (питон)

Подбор пароля к zip-файлу в Python

Выполняем заказ на фрилансе / Сайт для отслеживания криптовалют на Python

Как работать с архивами без установки архиватора. Штатный архиватор Windows

  • Купить a byte of python
  • Как вывести список без скобок в python
  • Python линейная регрессия
  • Python как управлять мышкой
  • Многооконное приложение pyqt
  • Как включить нумерацию строк в idle python
  • Python bootstrap пример
  • Django rest framework регистрация
  • Лемматизация русского текста python
  • Как сделать напоминалку на python
  • Django cms установка
  • 3 в python
  • Python установка keras
  • Кортежи в python
  • Python flask шаблоны

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Create and access rar archives.

miebach/lib-rar-python

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README

This is a fork of lib-rar-python written by miebach, with more options when archiving This package asissts using the command line version of rar on linux Install this module: sudo pip install librar-0.0.x.tar.gz (replace x with your version) You also need rar, on ubuntu: sudo aptitude install rar Usage example #!/usr/bin/python from librar import archive base="/home/me" # all files in archive will be relative to this path a = archive.Archive("/tmp/testarchive1.rar",base) # archive will be created in /tmp a.add_file("/home/me/testfile") # testfile will be added to archive a.set_password("awesomesauce") # set password to the archive a.set_compression_level(0) # change compression level to Store a.set_recovery_record(5) # set recovery record to 5% a.set_volume_size("50k") # split archive based on volume size 50 kilobytes # create archive: a.run() You can also add directories: a.add_dir("/home/me/dir1") # directory and everythin below it will be added to archive You can use add_dir and add_file multiple times and also combine them. To exclude directories or files: a.exclude("/home/me/dir1/tmp") # directory and everythin below it (?) will be excluded

About

Create and access rar archives.

Источник

Читайте также:  Python найти корень уравнения
Оцените статью