用Python将多个文件夹(在目录中)压缩到单个文件(在新目录中)

2024-04-25 21:49:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将多个文件夹(在一个目录中)压缩到各自的文件(而不是一个大的压缩文件)中,压缩到一个新目录中(与原始文件夹+'.zip'同名)

我对Python非常陌生,经过一些搜索,我得到了以下代码(在本视频https://www.youtube.com/watch?v=MjH5UFhDnnY&ab_channel=WebDevPro的帮助下):

import os, zipfile

os.chdir(r"C:\This\Is\An\Example")

for x in os.listdir():
    handle = zipfile.ZipFile(x + ".zip", "w")
    handle.write(x, compress_type = zipfile.ZIP_DEFLATED)
    handle.close()

我遇到的三个问题是,首先,我不知道如何将output/final_产品设置到一个新目录。其次,最终压缩的文件是空的-这是因为原始文件包含其他文件,脚本将原始文件中的文件更改为新名称(Folder001.zip)-如何在第一个/主文件夹停止脚本,使其不进入子文件夹。最后,循环似乎通过文件夹最多三次(请参考示例):

Folder001.zip

Folder001.zip.zip

Folder002.zip

Folder002.zip.zip

Folder002.zip.zip.zip

福德拉

FolderA.zip.zip

FolderA.zip.zip.zip

FolderB.zip

FolderB.zip.zip


Tags: 文件目录脚本文件夹osziphandle压缩文件
1条回答
网友
1楼 · 发布于 2024-04-25 21:49:15

在您的情况下,最好的方法可能是在路径中的所有目录上循环,并为每个目录创建一个zip文件,只在这些目录中添加文件(如果我了解您的问题的话)

因此,第一个问题是找到根文件夹中的所有目录。这可以通过使用根文件夹上的os.walk并查看其第一个输出的第二个元素来实现,该元素是根文件夹中所有文件夹的列表

然后,您必须为每个文件夹创建一个zip存档,只包含这些子文件夹的文件。同样,您可以在每个文件夹上使用os.walk,但这次查看其第一个输出的第三项,它对应于该文件夹中的文件列表

最好将问题分为两个不同的子问题:在根文件夹上循环和从文件夹创建zip文件

下面的代码段显示了函数在根文件夹上循环并为输出zip文件创建路径的可能实现:

def zip_subfolders(input_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)  # create output folder if it does not exist
    for folder_name in next(os.walk(input_folder))[1]:  # loop over all the folders in your input folder
        zipped_filepath = os.path.join(output_folder, f'{folder_name}.zip')  # create the path for the output zip file for this folder
        curr_folder_path = os.path.join(input_folder, folder_name)  # get the full path of the current folder
        create_zip(curr_folder_path, zipped_filepath)  # create the zip file and put in the right location

以下函数压缩每个子文件夹,添加文件夹第一级的所有文件:

def create_zip(folder_path, zipped_filepath):
    zip_obj = zipfile.ZipFile(zipped_filepath, 'w')  # create a zip file in the required path
    for filename in next(os.walk(folder_path))[2]: # loop over all the file in this folder
        zip_obj.write(
            os.path.join(folder_path, filename),  # get the full path of the current file
            filename,  # file path in the archive: we put all in the root of the archive
            compress_type=zipfile.ZIP_DEFLATED
        )
    zip_obj.close()

将所有内容放在一个脚本中:

import os
import zipfile

INPUT_FOLDER = 'to_zip'
OUTPUT_FOLDER = 'zipped'

def create_zip(folder_path, zipped_filepath):
    zip_obj = zipfile.ZipFile(zipped_filepath, 'w')  # create a zip file in the required path
    for filename in next(os.walk(folder_path))[2]: # loop over all the file in this folder
        zip_obj.write(
            os.path.join(folder_path, filename),  # get the full path of the current file
            filename,  # file path in the archive: we put all in the root of the archive
            compress_type=zipfile.ZIP_DEFLATED
        )
    zip_obj.close()

def zip_subfolders(input_folder, output_folder):
    os.makedirs(output_folder, exist_ok=True)  # create output folder if it does not exist
    for folder_name in next(os.walk(input_folder))[1]:  # loop over all the folders in your input folder
        zipped_filepath = os.path.join(output_folder, f'{folder_name}.zip')  # create the path for the output zip file for this folder
        curr_folder_path = os.path.join(input_folder, folder_name)  # get the full path of the current folder
        create_zip(curr_folder_path, zipped_filepath)  # create the zip file and put in the right location

if __name__ == '__main__':
    zip_subfolders(INPUT_FOLDER, OUTPUT_FOLDER)

相关问题 更多 >

    热门问题