简体   繁体   English

使用python zipfile不产生嵌套文件夹内的文件

[英]Not yielding files inside nested folders using python zipfile

Solved, check the marked answer Seems the one marked with os.walk() executes faster.解决了,检查标记的答案似乎用 os.walk()标记的答案执行得更快。

(Python 3.8, zipfile module, Windows 10 Anaconda) (Python 3.8,zipfile 模块,Windows 10 Anaconda)

I was using the zipfile module of python to create Zip Files of my folders.我正在使用 python 的zipfile模块来创建我的文件夹的 Zip 文件。

My Folder was D:/Personals.我的文件夹是 D:/Personals。 An os.listdir of personals yields 2 folders and 171 files.个人的os.listdir产生 2 个文件夹和 171 个文件。 When I checked the zip it contained all the 171 files of the folder and the 2 inner nested folders.当我检查 zip 时,它包含文件夹的所有 171 个文件和 2 个内部嵌套文件夹。 But the inner nested folders were empty, though each contained many individual files.但是内部嵌套文件夹是空的,尽管每个文件夹都包含许多单独的文件。 Here is my code.这是我的代码。

from zipfile import ZipFile 
from os import listdir 

dir_path = 'D:/Personals'
export_path = 'D:/Zipper'

items_list = listdir(dir_path)
zipper = ZipFile(export_path+'/S1.zip','w')

for item in items_list:
    zipper.write(dir_path+'/'+item)

zipper.close()

It has yielded all the files inside the folder but failed to return the files inside the 2 nested folders.它已生成文件夹内的所有文件,但未能返回 2 个嵌套文件夹内的文件。 Kindly advise what can I do?请告知我该怎么办?

Many thanks in advance.提前谢谢了。

When zipping folders using the ZipFile module, you must use recursion to include the subfolders.使用 ZipFile 模块压缩文件夹时,您必须使用递归来包含子文件夹。

Try this code:试试这个代码:

from zipfile import ZipFile 
from os import listdir, path

dir_path = 'D:/Personals'  # root folder to zip
export_path = 'D:/Zipper'  # target folder for zip file

items_list = listdir(dir_path)
zipper = ZipFile(export_path+'/S1.zip','w')

def addzipitems(zipper, folder):  # single folder
    for item in listdir(folder):  # each item (file or folder)
        zipper.write(folder+'/'+item)  # add item to zip (for folder, will add empty)
        if path.isdir(folder +'/'+item):  # if item is subfolder
            addzipitems(zipper, folder +'/'+item)   # process subfolder

addzipitems(zipper, dir_path)  # start at root folder
zipper.close()

You can also use os.walk to get all the files in a directory tree.您还可以使用os.walk来获取目录树中的所有文件。 No recursion needed.不需要递归。

from zipfile import ZipFile 
from os import listdir, path, walk

dir_path = 'D:/Personals'  # root folder to zip
export_path = 'D:/Zipper'  # target folder for zip file

zipper = ZipFile(export_path+'/S1.zip','w')

for path, directories, files in walk(dir_path): # all folders\files in tree
    for f in files:  # files is list
        zipper.write(path+'/'+f)

zipper.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM