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

move files from child directories (from unzipping) to parent directory in unzip step?

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

我可以在解压缩步骤中执行什么操作吗?

您可以单独提取文件,而不是使用 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 question and the tarfile docs

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

isfile() - 如果它不是一个文件,你不需要它。

member.name = os.path.basename(member.name) 重置子目录深度 - 提取器的东西都在顶层。