【发布时间】:2015-09-02 11:25:01
【问题描述】:
我正在尝试制作一个脚本,用于从一个目录中的文件夹中解压缩所有 .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)
【问题讨论】:
-
除非有使用 Python 的意义,否则这听起来像是最适合 shell 脚本的工作。
-
extractall 以目标目录为参数,无需来回chdir