我正在尝试制作一个脚本,用于从一个目录中的文件夹中解压缩所有.tar.gz文件.例如,我将调用一个文件(testing.tar.gz).然后,如果我手动操作,我可以按“提取”,然后.tar.gz文件将创建一个新文件,并调用testing.tar.最后,如果我重复按“提取这里”的过程,.tar文件会将所有.pdf文件生成.
我想知道我怎么能这样做,而且我的代码在这里,似乎并不是现实的工作.
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)