如何用python从.tar压缩包中提取一个特定的文件?

4 人关注

我在Linux机器上创建了一个.tar文件,内容如下。

tar cvf test.tar test_folder/

其中test_folder包含一些文件,如下图所示。

test_folder 
|___ file1.jpg
|___ file2.jpg
|___ ...

我无法用Python编程提取tar归档中的各个文件。更具体地说,我尝试了以下方法。

import tarfile
with tarfile.open('test.tar', 'r:') as tar:
    img_file = tar.extractfile('test_folder/file1.jpg')
    # img_file contains the object: <ExFileObject name='test_folder/test.tar'>

在这里,img_file似乎并不包含所要求的图像,而是包含源.tar文件。我不确定我在哪里弄错了。任何建议都将是非常有帮助的。谢谢。

3 个评论
为什么你认为它包含.tar文件?我刚刚尝试了按照你描述的步骤(尽管我不得不把tar命令的语法改为 tar cvf test.tar ./test_folder ),我能够用你的代码提取图像文件,没有任何问题,只要我使用相同的路径,即 './test_folder/filename'
注意,必须使用不同的路径是由于在Windows上的测试,刚刚在Debian上看了一下,你的tar语句和Python代码都能工作--请提供你认为代码不能工作的细节。你在 : 中包含 open 的参数,是否有什么原因?
python
tar
tarfile
Swaroop
Swaroop
发布于 2020-12-11
3 个回答
MarianD
MarianD
发布于 2020-12-11
已采纳
0 人赞同

你可能想使用 .extract() 方法,而不是你的 .extractfile() 方法(见我的 其他答案 ):

import tarfile
with tarfile.open('test.tar', 'r:') as tar:
    tar.extract('test_folder/file1.jpg')         # .extract()  instead of .extractfile()

Notes:

  • 你提取的文件将在你当前目录下的test_folder文件夹中(可能是新创建的)。

  • 替换代码0】方法返回None,所以不需要分配它(img_file = tar.extract(...))。

  • MarianD
    MarianD
    发布于 2020-12-11
    0 人赞同

    在你的代码中添加2行将解决你的问题。

    import tarfile
    with tarfile.open('test.tar', 'r:') as tar:
        img_file = tar.extractfile('test_folder/file1.jpg')
        # --------------------- Add this ---------------------------
        with open ("img_file.jpg", "wb") as outfile:
            outfile.write(img_file.read())
    

    The .extractfile() method only provided you the content的提取文件(即其数据).

            It don't extract any file to the file system.

    所以你要做的是yourself- 通过读取这些返回的内容(img_file.read())并将其写入你选择的文件(outfile.write(...))。

    或者--为了简化你的生活--用.extract()方法代替。见我的另一个答案.

    Charming-Deamon
    Charming-Deamon
    发布于 2020-12-11
    0 人赞同

    这是因为extractfile()返回一个io.BufferReader对象,所以本质上你是在提取你目录中的文件并将io.BufferReader存储在你的变量中。

    你可以做的是,提取文件,然后在一个不同的内容管理器中打开文件

    import tarfile
    with tarfile.open('test.tar', 'r:') as tar: