我很想知道我如何只压缩主目录中的所有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,而不包括任何其他文件夹/子文件夹。
您正在使用os.walk()
遍历整个目录树。听起来您只想查看给定目录中的文件。为此,考虑os.walk()
,它返回给定目录中所有文件和子目录的迭代器。您只需要过滤掉目录中的元素即可:
os.scandir()
您在对os.scandir()
的调用中隐式指定了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
,这将在存档中创建一个文件,其中包含您指定的路径,子目录以及所有路径。如果要添加到存档中的文件位于路径arcname
argument,则使用arcname
的定义,您的代码有效地转换为:
ZipFile.write()
由于/home/rob/Desktop/projects/zenjobv2/subdir1/subdir2/file.pdf
参数中包含目录分隔符,因此文件将被添加到名为os.path.relpath()
的子目录中的归档中。
您可能打算做这样的事情:
os.path.relpath()
这将使目录结构脱离存档。请注意,同名文件将被覆盖。