我有一個 .tar 檔案,其中包含一個檔案夾中的許多 .gz 檔案。這些 gz 檔案中的每一個都包含一個 .txt 檔案。與此問題相關的其他 stackoverflow 問題旨在提取檔案。
我試圖迭代讀取每個 .txt 檔案的內容而不提取它們,因為 .tar 很大。
首先我閱讀 .tar 檔案的內容:
import tarfile
tar = tarfile.open("FILE.tar")
tar.getmembers()
或者在 Unix 中:
tar xvf file.tar -O
然后我嘗試使用 tarfile 提取檔案方法,但出現錯誤:“模塊 '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
這是在使用 Mark Adler 的建議后對我有用的最終版本:
import tarfile
tar = tarfile.open("file.tar")
members = tar.getmembers()
# Here I append the results in a list, because I wasn't able to
# parse the tarfile type returned by .getmembers():
tar_name = []
for elem in members:
tar_name.append(elem.name)
# Then I changed tarfile.extractfile to tar.extractfile as suggested:
for member in tar_name:
# I'm using this because I have other non-gzs in the directory
if member.endswith(".gz"):
m=tar.extractfile(member)
file_contents = gzip.GzipFile(fileobj=m).read()
uj5u.com熱心網友回復:
您需要使用tar.extractfile(member)而不是tarfile.extractfile(member). tarfile是class,并且不知道您打開的 tar 檔案。tar是 tarfile物件,它參考您打開的 .tar 檔案。
要做到這一點,請使用next()而不是getmembers()or getnames(),這樣您就不必兩次讀取整個 tar 檔案:
with tarfile.open(sys.argv[1]) as tar:
while ent := tar.next():
if ent.name.endswith(".gz"):
print(gzip.GzipFile(fileobj=tar.extractfile(ent)).read())
uj5u.com熱心網友回復:
這是 unix line / 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:
* [email protected]:matthewmccullough/hellogitworld.git
* git://github.com/matthewmccullough/hellogitworld.git
* https://[email protected]/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= 提取 - flag
-O= 不要將檔案寫入檔案系統,而是寫入 STDOUT - flag
-f= 指定一個檔案
然后剩下的就是將結果傳送到 zcat 以查看 STDOUT 中未壓縮的明文
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/380099.html
