代码之家  ›  专栏  ›  技术社区  ›  MHeydt

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

  •  -1
  • MHeydt  · 技术社区  · 7 年前

    我有一个特别的问题: 我正在使用请求下载一些大型数据集。每个请求都向我提供一个压缩文件,其中包含下载清单,以及文件夹,每个文件夹包含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 回复  |  直到 7 年前
        1
  •  0
  •   Alan    7 年前

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

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

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

    member.name = os.path.basename(member.name) 重置子目录深度-提取器认为一切都处于顶层。