os.walk 制作目录并将 .zip 文件提取到新制作的目录中的最佳方法

问题描述 投票:0回答:1

假设我有一个根目录,里面有n个项目文件夹。每个项目文件夹包含一个 .zip 文件,其中包含 2 个文件:dpd.zip 和 lib.ear。

我想编写一个脚本,如果我将其放入根文件夹中,该脚本将迭代所有项目目录,并在每个项目中创建一个名为“core”的新目录,其中包含 2 个名为“zip”的子目录然后,脚本将提取项目目录中的 .zip 文件,将 dpd.zip 和 lib.ear 移动到创建的每个相关子文件夹中,最后提取内容并在工作完成后删除自身.

到目前为止我尝试过的:

import os
import shutil
import zipfile

def extract_zip(file_path, extract_to):
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)
    
for root, dirs, files in os.walk("."):
    for subdir in dirs:
        if not os.path.isdir(subdir + "core"):
            core_dir = subdir + "/core"
            ear_dir = core_dir + "/ear"
            zip_dir = core_dir + "/zip"
        
            os.mkdir(core_dir)
            os.mkdir(ear_dir)
            os.mkdir(zip_dir)
        
            # so far the tree was made inside each project`s folder
        
            for fl in os.listdir(subdir):
                file_path = os.path.join(subdir, fl)
                
                if fl.endswith(".zip") and os.path.isfile(file_path):
                    extract_zip(file_path, core_dir)
                    # so far extract the core .zip into the core folder of each project`s
                
                    # here comes the obstacle
        else:
            continue

障碍是当我尝试添加逻辑并将 .zip 和 .ear 的提取保留到其相对子目录中时。到目前为止,我唯一的解决方案是打开另一个特定于核心子目录的 for 循环,并为其中的文件(.zip/.ear/其他文件)添加逻辑,提取并删除提取的源。但是,由于根文件夹包含大量项目,因此该解决方案效率不高,并且将永远无法完成。

你认为这里有散步吗?

预先感谢您的支持。

python python-3.x scripting os.walk
1个回答
0
投票

我并没有真正使用你的整个脚本,但这是我的初步尝试。它适用于我,因此您可以检查它是否适合您。我手动形成路径(本来可以使用

os.path.join()
,但这样更快,如果这对你有用,我可以更改它)。

import os
import shutil
import zipfile

def extract_zip(file_path, extract_to):
    with zipfile.ZipFile(file_path, 'r') as zip_ref:
        zip_ref.extractall(extract_to)
    
for filename in os.listdir("."):
    f = os.path.join(".", filename)
    if os.path.isfile(f):
        continue

    core_dir = f + "/core"
    ear_dir = core_dir + "/ear"
    zip_dir = core_dir + "/zip"

    os.mkdir(core_dir)
    os.mkdir(ear_dir)
    os.mkdir(zip_dir)

    original_zip_file = ""

    # list all files in project folder
    for zip_file in os.listdir(f):
      potential_zip_file = f + "/" + zip_file

      # check if file iz indeed file and iz zip file
      if os.path.isfile(potential_zip_file) and potential_zip_file.endswith(".zip"):
        # extact it in project file
        extract_zip(potential_zip_file, f)
        original_zip_file = potential_zip_file

    dpd_zip = f + "/dpd.zip"
    ear = f + "/lib.ear"
      
    # move ear file directly in it's new folder (core/ear)  
    shutil.move(ear, ear_dir)
    # extact dpd.zip directly in it's new folder (core/zip)
    extract_zip(dpd_zip, zip_dir)
    
    os.remove(dpd_zip)
    os.remove(original_zip_file)
© www.soinside.com 2019 - 2024. All rights reserved.