将文件压缩到同一文件夹级别

Zipping files to the same folder level

此线程 here 建议使用 shutil 压缩文件:

import shutil
shutil.make_archive(output_filename, 'zip', dir_name)

这会压缩 dir_name 中的所有内容并保留其中的文件夹结构。是否可以使用同一个库删除所有子文件夹并将 dir_name 中的所有文件压缩到同一级别?或者我必须引入一个单独的代码块来首先合并文件吗?例如,这是一个假设的文件夹结构:

\dir_name
   \dir1
       \cat1
          file1.txt
          file2.txt
       \cat2
          file3.txt
   \dir2
       \cat3
          file4.txt

输出 zip 应该只包含:

file1.txt
file2.txt
file3.txt
file4.txt
# The root directory to search for
path = r'dir_name/'

import os
import glob

# List all *.txt files in the root directory
file_paths = [file_path 
              for root_path, _, _ in os.walk(path) 
              for file_path in glob.glob(os.path.join(root_path, '*.txt'))]

import tempfile

# Create a temporary directory to copy your files into
with tempfile.TemporaryDirectory() as tmp:
    import shutil

    for file_path in file_paths:
        # Get the basename of the file
        basename = os.path.basename(file_path)

        # Copy the file to the temporary directory  
        shutil.copyfile(file_path, os.path.join(tmp, basename))

    # Zip the temporary directory to the working directory
    shutil.make_archive('output', 'zip', tmp)

这将在当前工作目录中创建一个 output.zip 文件。到达上下文管理器末尾时将删除临时目录。

shutil.make_archive 没有办法在不将文件复制到另一个目录的情况下做你想做的事,这是低效的。相反,您可以直接使用类似于您提供的链接答案的压缩库。请注意,这不会处理名称冲突!

import zipfile
import os

with zipfile.ZipFile('output.zip','w',zipfile.ZIP_DEFLATED,compresslevel=9) as z:
    for path,dirs,files in os.walk('dir_name'):
        for file in files:
            full = os.path.join(path,file)
            z.write(full,file) # write the file, but with just the file's name not full path

# print the files in the zipfile
with zipfile.ZipFile('output.zip') as z:
    for name in z.namelist():
        print(name)

鉴于:

dir_name
├───dir1
│   ├───cat1
│   │       file1.txt
│   │       file2.txt
│   │
│   └───cat2
│           file3.txt
│
└───dir2
    └───cat3
            file4.txt

输出:

file1.txt
file2.txt
file3.txt
file4.txt