python 解压缩tar.gz文件_我想通过(Python)为解压缩(.tar.gz)文件创建脚本

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)

解决方案

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值