我想通过(Python)创建用于解压缩(.tar.gz)文件的脚本 [英] I want to create a script for unzip (.tar.gz) file via (Python)

查看:554
本文介绍了我想通过(Python)创建用于解压缩(.tar.gz)文件的脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个脚本,用于从一个目录中的文件夹解压缩所有.tar.gz文件.例如,我将有一个文件称为(testing.tar.gz).然后,如果我手动进行操作,则可以按此处提取",然后.tar.gz文件将创建一个新文件,并调用testing.tar.最后,如果我重复按在此处提取"的过程,那么.tar文件将使我拥有所有.pdf文件.

I am trying to make a script for unzipping all the .tar.gz files from folders in one directory. For example, I will have a file which it calls ( testing.tar.gz). Then if I do manually, I can press to "extract here" then the .tar.gz file will create a new file, and it calls testing.tar. Finally, if I repeat the process of pressing "extract here", the .tar file prodcudes me all the .pdf files.

我想知道我该怎么做,并且我的代码在这里,似乎无法实现.

I wonder that how can I do it, and I have my code here and it seems doesn't realty work tho.

import os
import tarfile
import zipfile

def extract_file(path, to_directory='.'):
    if path.endswith('.zip'):
        opener, mode = zipfile.ZipFile, 'r'
    elif path.endswith('.tar.gz') or path.endswith('.tgz'):
        opener, mode = tarfile.open, 'r:gz'
    elif path.endswith('.tar.bz2') or path.endswith('.tbz'):
        opener, mode = tarfile.open, 'r:bz2'
    else: 
        raise ValueError, "Could not extract `%s` as no appropriate extractor is found" % path

    cwd = os.getcwd()
    os.chdir(to_directory)

    try:
        file = opener(path, mode)
        try: file.extractall()
        finally: file.close()
    finally:
        os.chdir(cwd)

推荐答案

为什么要一次轻松地两次按".tar.gz"提取一个.tar.gz?这是一个一次性提取.tar和.tar.gz的简单代码:

Why do you want to "press" twice to extract a .tar.gz, when you can easily do it once? Here is a simple code to extract both .tar and .tar.gz in one go:

import tarfile

if fname.endswith("tar.gz"):
    tar = tarfile.open(fname, "r:gz")
    tar.extractall()
    tar.close()
elif fname.endswith("tar"):
    tar = tarfile.open(fname, "r:")
    tar.extractall()
    tar.close()

这篇关于我想通过(Python)创建用于解压缩(.tar.gz)文件的脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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