簡體   English   中英

讀取.tar文件里面的.gz文件而不解壓

[英]Read .gz files inside .tar files without extracting

我有一個 .tar 文件,其中包含一個文件夾中的許多 .gz 文件。 這些 gz 文件中的每一個都包含一個 .txt 文件。 與此問題相關的其他 stackoverflow 問題旨在提取文件。

我正在嘗試迭代讀取 each.txt 文件的內容而不提取它們,因為 .tar 很大。

首先我閱讀了 .tar 文件的內容:

import tarfile
tar = tarfile.open("FILE.tar")
tar.getmembers()

或者在 Unix 中:

tar xvf file.tar -O

然后我嘗試使用 tarfile extractfile 方法,但出現錯誤:“模塊 'tarfile' 沒有屬性 'extractfile'”。 此外,我什至不確定這是正確的方法。

import gzip
for member in tar.getmembers():
    m = tarfile.extractfile(member)
    file_contents = gzip.GzipFile(fileobj=m).read()

如果要創建示例文件來模擬原始文件:

$ mkdir directory
$ touch directory/file1.txt.gz directory/file2.txt.gz directory/file3.txt.gz
$ tar -c -f file.tar directory

編輯:我正在編寫 Python 腳本,但 Unix 行也可以。

這是 unix 行 / bash 命令:

准備文件:

$ git clone https://github.com/githubtraining/hellogitworld.git
$ cd hellogitworld
$ gzip *
$ ls
build.gradle.gz  fix.txt.gz  pom.xml.gz  README.txt.gz  resources  runme.sh.gz  src
$ cd ..
$ tar -cf hellogitworld.tar hellogitworld/

以下是查看其自述文件的方法:

$ tar -Oxf hellogitworld.tar hellogitworld/README.txt.gz | zcat

結果:

This is a sample project students can use during Matthew's Git class.

Here is an addition by me

We can have a bit of fun with this repo, knowing that we can always reset it to a known good state.  We can apply labels, and branch, then add new code and merge it in to the master branch.

As a quick reminder, this came from one of three locations in either SSH, Git, or HTTPS format:

* git@github.com:matthewmccullough/hellogitworld.git
* git://github.com/matthewmccullough/hellogitworld.git
* https://matthewmccullough@github.com/matthewmccullough/hellogitworld.git

We can, as an example effort, even modify this README and change it as if it were source code for the purposes of the class.

This demo also includes an image with changes on a branch for examination of image diff on GitHub.

請注意,我與那些 git 存儲庫無關。

焦油的解釋:

  • 標志-x = 提取
  • 標志-O = 不將文件寫入文件系統但寫入 STDOUT
  • flag -f = 指定一個文件

然后 rest 只是將結果傳送到 zcat 以在 STDOUT 中查看未壓縮的明文

您需要使用tar.extractfile(member)而不是tarfile.extractfile(member) tarfileclass ,不知道您打開的 tar 文件。 tar是 tar 文件object ,它引用了您打開的 .tar 文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM