Python:压缩目录中的所有文件夹 [英] Python: zip all folders in directory

查看:35
本文介绍了Python:压缩目录中的所有文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我知道目录的路径,我如何单独压缩其中的所有文件夹?我尝试了一些东西,但由于我不完全了解 os 模块的工作原理,因此我无能为力.

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.

示例:

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

我想要得到的是folder1.zip(包含文件1.1)、folder2.zip(包含文件2.1)和folder2.zip(包含文件3.1和文件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

感谢任何帮助.

推荐答案

我认为问题在于您为 zip 存档中的每个文件指定了不同的 arcname(<代码>编写方法).尝试以下操作(我还替换了一些代码,如使用 os.path 模块而不是字符串连接的路径连接):

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()

这篇关于Python:压缩目录中的所有文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆