Python zipfile库创建一个zip,其中只包含一个目录中的.pdf和.xml文件

2024-05-14 17:46:10 发布

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

我很想知道如何只压缩主目录中的所有PDF而不包括子文件夹。你知道吗

我试过几次修改代码,但都没有成功。你知道吗

import zipfile

fantasy_zip = zipfile.ZipFile('/home/rob/Desktop/projects/zenjobv2/archivetest.zip', 'w')

for folder, subfolders, files in os.walk('/home/rob/Desktop/projects/zenjobv2/'):

    for file in files:
        if file.endswith('.pdf'):
            fantasy_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), '/home/rob/Desktop/projects/zenjobv2/'), compress_type = zipfile.ZIP_DEFLATED)
        elif file.endswith('.xml'):
            fantasy_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), '/home/rob/Desktop/projects/zenjobv2/'), compress_type = zipfile.ZIP_DEFLATED)
fantasy_zip.close()

我希望只使用zenjobv2文件夹/目录中的.pdfs和.xml文件创建zip,而不包括任何其他文件夹/子文件夹。你知道吗

(已编辑)解决方案:

import os, glob
import zipfile

fantasy_zip = zipfile.ZipFile('/home/rob/Desktop/projects/zenjobv2/archivetest.zip', 'w')

root = "/home/rob/Desktop/projects/zenjobv2"

for file in os.listdir(root):
    if file.endswith('.pdf') or file.endswith(".xml"):
        fantasy_zip.write(file)
fantasy_zip.close()

Tags: path文件夹homeosfolderzipfantasyfile
1条回答
网友
1楼 · 发布于 2024-05-14 17:46:10

更新了OP的新信息:

您正在使用^{}遍历整个目录树。听起来你只是想看看给定目录中的文件。为此,考虑^{},它返回给定目录中所有文件和子目录的迭代器。您只需过滤掉目录中的元素:

root = "/home/rob/Desktop/projects/zenjobv2"
for entry in os.scandir(root):
    if entry.is_dir():
        continue  # Just in case there are strangely-named directories
    if entry.path.endswith(".pdf") or entry.path.endswith(".xml"):
        # Process the file at entry.path as you see fit

之前的回答是基于对问题的不理解:

您在对ZipFile.write()的调用中隐式地指定了^{} argument,这将在归档文件中创建一个文件,其中包含您给定的路径、子目录和所有内容。如果要添加到存档中的文件位于路径/home/rob/Desktop/projects/zenjobv2/subdir1/subdir2/file.pdf,那么使用^{}的定义,代码可以有效地转换为:

fantasy_zip.write("/home/rob/Desktop/projects/zenjobv2/subdir1/subdir2/file.pdf",
                  arcname="subdir1/subdir2/file.pdf",
                  compress_type=zipfile.ZIP_DEFLATED)

因为arcname参数中有目录分隔符,所以文件将被添加到名为subdir1/subdir2的子目录中的存档中。你知道吗

你可能打算这样做:

fantasy_zip.write(os.path.join(folder, file), arcname=file)

这将使目录结构不在存档中。不过,请注意,同名文件将被覆盖。你知道吗

相关问题 更多 >

    热门问题