Python: zip all folders in directory

安稳与你 提交于 2020-06-26 06:24:21

问题


If I know the path of the directory, how can I zip separately all the folders in it? I tried something, but since I don't fully understand how the os module works, there's not much I can do.

import os, zipfile

directory_path = str(raw_input())
for folder in os.listdir(directory_path):
    zip_file = zipfile.ZipFile(folder + '.zip', 'w')
    for root, dirs, files in os.walk(directory_path+'/'+folder):
        for file in files:
            zip_file.write(os.path.join(root, file),file)
    zip_file.close()

The problem is that it only zips one folder from the directory.

Example:

Directory
 |
 +-- folder1
 |  |  
 |  \-- file 1.1
 |
 +-- folder2
 |  |  
 |  \-- file 2.1
 |    
 +-- folder3
 |  |  
 |  +-- file 3.1
 |  \-- file 3.2

What I want to get is folder1.zip (contains file 1.1), folder2.zip (contains file 2.1) and folder2.zip (contains file 3.1 and file 3.2

Any help is appreciated.


回答1:


I think that the problem is that you are specifying a different arcname for every file in the zip archive (2nd parameter of the write method). Try the following (I also replaced some code like paths joining using os.path module instead of string concatenation):

import os
import zipfile

path = raw_input('Enter the directory: ')
path = os.path.abspath(os.path.normpath(os.path.expanduser(path)))
for folder in os.listdir(path):
    zipf = zipfile.ZipFile('{0}.zip'.format(os.path.join(path, folder)), 'w', zipfile.ZIP_DEFLATED)
    for root, dirs, files in os.walk(os.path.join(path, folder)):
        for filename in files:
            zipf.write(os.path.abspath(os.path.join(root, filename)), arcname=filename)
    zipf.close()


来源:https://stackoverflow.com/questions/34153166/python-zip-all-folders-in-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!