在Python中使用rarfile从RAR存档中提取单个文件 [英] Extract single file from RAR archive with rarfile in Python

查看:160
本文介绍了在Python中使用rarfile从RAR存档中提取单个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含2个文件的RAR存档,我只想提取其中一个.我在另一个答案中发现可以使用 rarfile 包,根据

I have a RAR archive with 2 files and I want to extract only one. I found in another answer that I could use the rarfile package, which according to the documentation contains the extract function. However, when I try to run a script I get a FileNotFoundError: [WinError 2] and the following information: During handling of the above exception, another exception occurred: ... rarfile.RarCannotExec: Unrar not installed? (rarfile.UNRAR_TOOL='unrar').

从我能找到的信息中,我看到它可能与PATH中缺少 Unrar.exe 可执行文件有关,因此我尝试添加它,但未做任何更改.另一个建议是在脚本中添加 rarfile.UNRAR_TOOL ='unrar'作为配置程序包行为的一种方式,同样是同样的错误.

From the information I could find, I saw it could be related with the absence of the Unrar.exe executable in the PATH and I tried to add it, but nothing changed. Another suggestion was to add rarfile.UNRAR_TOOL='unrar' to the script as a way to configure the behavior of the package, again same error.

这是我用Python 3.5.3编写和测试的MWE:

This is my MWE, written and tested in Python 3.5.3:

from rarfile import RarFile

with RarFile('Test.rar') as file:
    file.extract(file.namelist()[0])

由于 file.namelist()返回档案的内容,因此文件正在正确打开.

The file is being properly opened, since file.namelist() returns the archive's contents.

提前谢谢!

推荐答案

基于OP注释进行更新:

我使用以下代码设法仅解压缩了一个文件

I managed to unpack just one file using the following code

from rarfile import RarFile
RarFile.UNRAR_TOOL='C:\\full\\path\\to\\UnRARDLL.exe'

with RarFile('test.rar') as file:
    file.extract(file.namelist()[0])

下载 UnRARDLL.exe 并提供 RarFile的正确完整路径.UNRAR_TOOL .

您可能要使用 patool

import patoolib
patoolib.extract_archive("Test.rar", outdir="/some/dir")


可在 windows linux 上运行,不需要额外的软件.
要安装,请使用: pip install patool


Works on windows and linux, no extra software needed.
To install use: pip install patool

这篇关于在Python中使用rarfile从RAR存档中提取单个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆