简体   繁体   English

Python:压缩文件夹和文件

[英]Python: Zipping a Folder + File

I have a folder structure like this: C:\\Users\\Simon\\Desktop\\mySoftware\\files\\output\\ 我有一个像这样的文件夹结构:C:\\ Users \\ Simon \\ Desktop \\ mySoftware \\ files \\ output \\

In the output folder, there is a file and a folder with another file in. 在输出文件夹中,有一个文件和一个包含另一个文件的文件夹。

I need Python to compress the files (and the folder) inside the 'output' folder. 我需要Python来压缩“输出”文件夹中的文件(和文件夹)。

I tried the following: 我尝试了以下方法:

#!/usr/bin/env python
import os, zipfile

simonsFiles = 'C:\Users\Simon\Desktop\mySoftware\files\output\\'

simonsZip = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk(simonsFiles):
    simonsZip.write(dirname)
    for filename in files:
        simonsZip.write(os.path.join(dirname, filename))
simonsZip.close()

But Python creates a zip folder in with the entire structure: 但是Python在其中创建具有整个结构的zip文件夹:

Users\\Simon\\Desktop\\mySoftware\\files\\output\\ 用户\\西蒙\\桌面\\ mySoftware \\文件\\输出\\

and when I get to output, it has the folder and the file that I wanted to compress to zip. 当我输出时,它包含我想压缩为zip的文件夹和文件。

How can I make Python compress the folder and the file into a zip rather than the entire directory structure? 如何让Python将文件夹和文件压缩为zip而不是整个目录结构?

You probably want to provide the second, optional, parameter arcname to zf.write() ( http://docs.python.org/2/library/zipfile#zipfile.ZipFile.write ). 您可能想向zf.write()提供第二个可选的参数arcnamehttp://docs.python.org/2/library/zipfile#zipfile.ZipFile.write )。 The following function works for me: 以下功能对我有用:

def zip_dir(zipname, dir_to_zip):
    dir_to_zip_len = len(dir_to_zip.rstrip(os.sep)) + 1
    with zipfile.ZipFile(zipname, mode='w', compression=zipfile.ZIP_DEFLATED) as zf:
        for dirname, subdirs, files in os.walk(dir_to_zip):
            for filename in files:
                path = os.path.join(dirname, filename)
                entry = path[dir_to_zip_len:]
                zf.write(path, entry)

This function does not archive empty subdirectories, for this to work you would have to iterate over files+subdirs in the second for loop. 此函数不会存档空的子目录,要使此方法起作用,您将不得不在第二个for循环中遍历files + subdirs。

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

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