簡體   English   中英

如何使用 python 2.4 提取 tar 文件?

[英]How do I extract a tar file using python 2.4?

我正在嘗試使用 python 2.4.2 完全提取 .tar 文件,因此並非 tarfile 模塊的所有方面都可用。 我瀏覽了 python 紀錄片,但我沒有發現它對我有幫助,因為我繼續犯語法錯誤。 以下是我嘗試過的命令(沒有成功):

tarfile.Tarfile.getnames(tarfile.tar)
tarfile.Tarfile.extract(tarfile.tar)

有沒有一種簡單的方法可以完全提取我的焦油? 如果是這樣,使用的格式是什么? 另外,我想指出 tarfile.TarFile.extractall() 在我的 python 版本中不可用。

此示例來自tarfile文檔。

import tarfile
tar = tarfile.open("sample.tar.gz")
tar.extractall()
tar.close()

首先,使用在創建tar文件對象tarfile.open()然后將所有文件是使用提取extractall()最后是對象被關閉。

如果要提取到其他目錄,請使用extractallpath參數

tar.extractall(path='/home/connor/')

編輯:我現在看到您使用的是沒有TarFile.extractall()方法的舊 Python 版本。 tarfile 舊版本文檔證實了這一點。 您可以改為執行以下操作:

for member in tar.getmembers():
    print "Extracting %s" % member.name
    tar.extract(member, path='/home/connor/')

如果您的 tar 文件中有目錄,這可能會失敗(我還沒有測試過)。 為了更完整的解決方案,請參閱Python 2.7版執行的extractall

編輯 2:對於使用舊 Python 版本的簡單解決方案,請使用subprocess.call調用tar 命令

import subprocess
tarfile = '/path/to/myfile.tar'
path = '/home/connor'
retcode = subprocess.call(['tar', '-xvf', tarfile, '-C', path])
if retcode == 0:
    print "Extracted successfully"
else:
    raise IOError('tar exited with code %d' % retcode)

這是來自torchvision 庫的更通用的代碼:

import os
import hashlib
import gzip
import tarfile
import zipfile

def _is_tarxz(filename):
    return filename.endswith(".tar.xz")


def _is_tar(filename):
    return filename.endswith(".tar")


def _is_targz(filename):
    return filename.endswith(".tar.gz")


def _is_tgz(filename):
    return filename.endswith(".tgz")


def _is_gzip(filename):
    return filename.endswith(".gz") and not filename.endswith(".tar.gz")


def _is_zip(filename):
    return filename.endswith(".zip")


def extract_archive(from_path, to_path=None, remove_finished=False):
    if to_path is None:
        to_path = os.path.dirname(from_path)

    if _is_tar(from_path):
        with tarfile.open(from_path, 'r') as tar:
            tar.extractall(path=to_path)
    elif _is_targz(from_path) or _is_tgz(from_path):
        with tarfile.open(from_path, 'r:gz') as tar:
            tar.extractall(path=to_path)
    elif _is_tarxz(from_path):
        with tarfile.open(from_path, 'r:xz') as tar:
            tar.extractall(path=to_path)
    elif _is_gzip(from_path):
        to_path = os.path.join(to_path, os.path.splitext(os.path.basename(from_path))[0])
        with open(to_path, "wb") as out_f, gzip.GzipFile(from_path) as zip_f:
            out_f.write(zip_f.read())
    elif _is_zip(from_path):
        with zipfile.ZipFile(from_path, 'r') as z:
            z.extractall(to_path)
    else:
        raise ValueError("Extraction of {} not supported".format(from_path))

    if remove_finished:
        os.remove(from_path)

暫無
暫無

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

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