在解压缩步骤中将文件从子目录(从解压缩)移动到父目录?

时间:2018-03-12 16:14:57

标签: python shutil tarfile

我遇到了一个具体问题: 我正在使用请求下载一些大型数据集。每个请求都为我提供了一个压缩文件,其中包含下载清单和文件夹,每个文件夹包含1个文件。

我可以解压缩存档+删除存档,然后从子目录中提取所有文件+删除子目录。

有没有办法结合这个?由于我对这两个动作都不熟悉,因此我研究了两个主题的教程和堆栈溢出问题。我很高兴它正在运行,但我想改进我的代码并可能将这两个步骤结合起来 - 我在浏览其他信息时没有遇到它。

因此,对于每组参数,我执行的请求最终为:

# Write the file
with open((file_location+file_name), "wb") as output_file:
    output_file.write(response.content)
# Unzip it
with tarfile.open((file_location+file_name), "r:gz") as tarObj:
    tarObj.extractall(path=file_location)
# Remove compressed file
os.remove(file_location+file_name)

然后在下一步我编写了一个函数:

target_dir = keyvalue[1] # target directory is stored in this tuple
subdirs = get_imm_subdirs(target_dir) # function to get subdirectories
for f in subdirs:
    c = os.listdir(os.path.join(target_dir, f)) # find file in subdir
    shutil.move(c, str(target_dir)+"ALL_FILES/") # move them into 1 subdir
os.rmdir([os.path.join(target_dir, x) for x in subdirs]) # remove other subdirs

在解压缩步骤中是否可以执行某个操作?

1 个答案:

答案 0 :(得分:0)

您可以单独提取文件,而不是使用extractall

with tarfile.open('musthaves.tar.gz') as tarObj:
    for member in tarObj.getmembers():
        if member.isfile():
            member.name = os.path.basename(member.name)
            tarObj.extract(member, ".")

适当归功于this SO questiontarfile docs

getmembers()将提供列表中的内容(作为对象);您可以使用listnames()但是您必须自己设计测试,以确定每个条目是否是文件或目录。

isfile() - 如果它不是文件,则不需要它。

member.name = os.path.basename(member.name)重置子目录深度 - 提取器内容一切都在顶层。