使用 python 将文件夹添加到 zip 文件

发布于 2024-07-12 13:54:35 字数 1883 浏览 4 评论 0原文

我想创建一个 zip 文件。 将文件夹添加到 zip 文件,然后将一堆文件添加到该文件夹​​。

所以我想最终得到一个 zip 文件,其中包含一个包含文件的文件夹。

我不知道在 zip 文件中包含文件夹是否是不好的做法,但谷歌没有给我任何关于这个主题的信息。

我从这个开始:

def addFolderToZip(myZipFile,folder):
    folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
    for file in glob.glob(folder+"/*"):
            if os.path.isfile(file):
                print file
                myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
            elif os.path.isdir(file):
                addFolderToZip(myZipFile,file)

def createZipFile(filename,files,folders):
    curTime=strftime("__%Y_%m_%d", time.localtime())
    filename=filename+curTime;
    print filename
    zipFilename=utils.getFileName("files", filename+".zip")
    myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing 
    for file in files:
        file = file.encode('ascii') #convert path to ascii for ZipFile Method
        if os.path.isfile(file):
            (filepath, filename) = os.path.split(file)
            myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )

    for folder in  folders:   
        addFolderToZip(myZipFile,folder)  
    myZipFile.close()
    return (1,zipFilename)


(success,filename)=createZipFile(planName,files,folders);

取自: http://mail. python.org/pipermail/python-list/2006-August/396166.html

它将删除所有文件夹并将目标文件夹(及其子文件夹)中的所有文件放入单个 zip 文件中。 我无法让它添加整个文件夹。

如果我将路径提供给 myZipFile.write 中的文件夹,我会得到

IOError:[Errno 13]权限被拒绝:'..\packed\bin'

非常欢迎任何帮助。

相关问题:如何我是否使用 python(版本 2.5)压缩文件夹的内容?

I want to create a zip file. Add a folder to the zip file and then add a bunch of files to that folder.

So I want to end up with a zip file with a single folder with files in.

I dont know if its bad practice to have folders in zip files or something but google gives me nothing on the subject.

I started out with this:

def addFolderToZip(myZipFile,folder):
    folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
    for file in glob.glob(folder+"/*"):
            if os.path.isfile(file):
                print file
                myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
            elif os.path.isdir(file):
                addFolderToZip(myZipFile,file)

def createZipFile(filename,files,folders):
    curTime=strftime("__%Y_%m_%d", time.localtime())
    filename=filename+curTime;
    print filename
    zipFilename=utils.getFileName("files", filename+".zip")
    myZipFile = zipfile.ZipFile( zipFilename, "w" ) # Open the zip file for writing 
    for file in files:
        file = file.encode('ascii') #convert path to ascii for ZipFile Method
        if os.path.isfile(file):
            (filepath, filename) = os.path.split(file)
            myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )

    for folder in  folders:   
        addFolderToZip(myZipFile,folder)  
    myZipFile.close()
    return (1,zipFilename)


(success,filename)=createZipFile(planName,files,folders);

Taken from: http://mail.python.org/pipermail/python-list/2006-August/396166.html

Which gets rid of all folders and puts all files in the target folder (and its subfolders) into a single zip file. I couldnt get it to add an entire folder.

If I feed the path to a folder in myZipFile.write, I get

IOError: [Errno 13] Permission denied: '..\packed\bin'

Any help is much welcome.

Related question: How do I zip the contents of a folder using python (version 2.5)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(13

走走停停 2024-07-19 13:54:35

您还可以使用 Shutil

import shutil

zip_name = 'path\to\zip_file'
directory_name = 'path\to\directory'

# Create 'path\to\zip_file.zip'
shutil.make_archive(zip_name, 'zip', directory_name)

这会将整个文件夹放入 zip 中。

You can also use shutil

import shutil

zip_name = 'path\to\zip_file'
directory_name = 'path\to\directory'

# Create 'path\to\zip_file.zip'
shutil.make_archive(zip_name, 'zip', directory_name)

This will put the whole folder in the zip.

一袭白衣梦中忆 2024-07-19 13:54:35

好吧,在我明白你想要什么之后,就像使用 zipfile.write 的第二个参数一样简单,你可以使用你想要的任何东西:

import zipfile
myZipFile = zipfile.ZipFile("zip.zip", "w" )
myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED )

创建一个 zipfile 其中 test.py 将被提取到名为 dir 的目录

编辑:
我曾经不得不在 zip 文件中创建一个空目录:这是可能的。
上面的代码只需从 zip 文件中删除文件 test.py 后,该文件就消失了,但空目录仍然存在。

Ok, after i understood what you want, it is as simple as using the second argument of zipfile.write, where you can use whatever you want:

import zipfile
myZipFile = zipfile.ZipFile("zip.zip", "w" )
myZipFile.write("test.py", "dir\\test.py", zipfile.ZIP_DEFLATED )

creates a zipfile where test.py would be extracted to a directory called dir

EDIT:
I once had to create an empty directory in a zip file: it is possible.
after the code above just delete the file test.py from the zipfile, the file is gone, but the empty directory stays.

泛泛之交 2024-07-19 13:54:35

zip 文件没有目录结构,它只有一堆路径名及其内容。 这些路径名应该相对于虚构的根文件夹(ZIP 文件本身)。 “../”前缀在 zip 文件中没有定义的含义。

假设您有一个文件 a,并且您希望将其存储在 zip 文件内的“文件夹”中。 您所要做的就是在将文件存储在 zip 文件中时在文件名前加上文件夹名称前缀:

zipi= zipfile.ZipInfo()
zipi.filename= "folder/a" # this is what you want
zipi.date_time= time.localtime(os.path.getmtime("a"))[:6]
zipi.compress_type= zipfile.ZIP_DEFLATED
filedata= open("a", "rb").read()

zipfile1.writestr(zipi, filedata) # zipfile1 is a zipfile.ZipFile instance

我不知道有任何 ZIP 实现允许在 ZIP 文件中包含文件夹。 我可以想到一种解决方法(在 zip“文件夹”中存储一个虚拟文件名,在提取时应忽略该文件名),但不能跨实现移植。

A zip file has no directory structure, it just has a bunch of pathnames and their contents. These pathnames should be relative to an imaginary root folder (the ZIP file itself). "../" prefixes have no defined meaning in a zip file.

Consider you have a file, a and you want to store it in a "folder" inside a zip file. All you have to do is prefix the filename with a folder name when storing the file in the zipfile:

zipi= zipfile.ZipInfo()
zipi.filename= "folder/a" # this is what you want
zipi.date_time= time.localtime(os.path.getmtime("a"))[:6]
zipi.compress_type= zipfile.ZIP_DEFLATED
filedata= open("a", "rb").read()

zipfile1.writestr(zipi, filedata) # zipfile1 is a zipfile.ZipFile instance

I don't know of any ZIP implementations allowing the inclusion of an empty folder in a ZIP file. I can think of a workaround (storing a dummy filename in the zip "folder" which should be ignored on extraction), but not portable across implementations.

新雨望断虹 2024-07-19 13:54:35
import zipfile
import os


class ZipUtilities:

    def toZip(self, file, filename):
        zip_file = zipfile.ZipFile(filename, 'w')
        if os.path.isfile(file):
                    zip_file.write(file)
            else:
                    self.addFolderToZip(zip_file, file)
        zip_file.close()

    def addFolderToZip(self, zip_file, folder): 
        for file in os.listdir(folder):
            full_path = os.path.join(folder, file)
            if os.path.isfile(full_path):
                print 'File added: ' + str(full_path)
                zip_file.write(full_path)
            elif os.path.isdir(full_path):
                print 'Entering folder: ' + str(full_path)
                self.addFolderToZip(zip_file, full_path)

def main():
    utilities = ZipUtilities()
    filename = 'TEMP.zip'
    directory = 'TEMP'
    utilities.toZip(directory, filename)

main()

我正在运行:

python tozip.py

这是日志:

havok@fireshield:~$ python tozip.py

File added: TEMP/NARF (7ª copia)
Entering folder: TEMP/TEMP2
File added: TEMP/TEMP2/NERF (otra copia)
File added: TEMP/TEMP2/NERF (copia)
File added: TEMP/TEMP2/NARF
File added: TEMP/TEMP2/NARF (copia)
File added: TEMP/TEMP2/NARF (otra copia)
Entering folder: TEMP/TEMP2/TEMP3
File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL
File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL (copia)
File added: TEMP/TEMP2/NERF
File added: TEMP/NARF (copia) (otra copia)
File added: TEMP/NARF (copia) (copia)
File added: TEMP/NARF (6ª copia)
File added: TEMP/NERF (copia) (otra copia)
File added: TEMP/NERF (4ª copia)
File added: TEMP/NERF (otra copia)
File added: TEMP/NERF (3ª copia)
File added: TEMP/NERF (6ª copia)
File added: TEMP/NERF (copia)
File added: TEMP/NERF (5ª copia)
File added: TEMP/NARF (8ª copia)
File added: TEMP/NARF (3ª copia)
File added: TEMP/NARF (5ª copia)
File added: TEMP/NERF (copia) (3ª copia)
File added: TEMP/NARF
File added: TEMP/NERF (copia) (copia)
File added: TEMP/NERF (8ª copia)
File added: TEMP/NERF (7ª copia)
File added: TEMP/NARF (copia)
File added: TEMP/NARF (otra copia)
File added: TEMP/NARF (4ª copia)
File added: TEMP/NERF
File added: TEMP/NARF (copia) (3ª copia)

如您所见,它可以工作,存档也可以。 这是一个递归函数,可以压缩整个文件夹。 唯一的问题是它不会创建空文件夹。

干杯。

import zipfile
import os


class ZipUtilities:

    def toZip(self, file, filename):
        zip_file = zipfile.ZipFile(filename, 'w')
        if os.path.isfile(file):
                    zip_file.write(file)
            else:
                    self.addFolderToZip(zip_file, file)
        zip_file.close()

    def addFolderToZip(self, zip_file, folder): 
        for file in os.listdir(folder):
            full_path = os.path.join(folder, file)
            if os.path.isfile(full_path):
                print 'File added: ' + str(full_path)
                zip_file.write(full_path)
            elif os.path.isdir(full_path):
                print 'Entering folder: ' + str(full_path)
                self.addFolderToZip(zip_file, full_path)

def main():
    utilities = ZipUtilities()
    filename = 'TEMP.zip'
    directory = 'TEMP'
    utilities.toZip(directory, filename)

main()

I'm running:

python tozip.py

This is the log:

havok@fireshield:~$ python tozip.py

File added: TEMP/NARF (7ª copia)
Entering folder: TEMP/TEMP2
File added: TEMP/TEMP2/NERF (otra copia)
File added: TEMP/TEMP2/NERF (copia)
File added: TEMP/TEMP2/NARF
File added: TEMP/TEMP2/NARF (copia)
File added: TEMP/TEMP2/NARF (otra copia)
Entering folder: TEMP/TEMP2/TEMP3
File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL
File added: TEMP/TEMP2/TEMP3/DOCUMENTO DEL FINAL (copia)
File added: TEMP/TEMP2/NERF
File added: TEMP/NARF (copia) (otra copia)
File added: TEMP/NARF (copia) (copia)
File added: TEMP/NARF (6ª copia)
File added: TEMP/NERF (copia) (otra copia)
File added: TEMP/NERF (4ª copia)
File added: TEMP/NERF (otra copia)
File added: TEMP/NERF (3ª copia)
File added: TEMP/NERF (6ª copia)
File added: TEMP/NERF (copia)
File added: TEMP/NERF (5ª copia)
File added: TEMP/NARF (8ª copia)
File added: TEMP/NARF (3ª copia)
File added: TEMP/NARF (5ª copia)
File added: TEMP/NERF (copia) (3ª copia)
File added: TEMP/NARF
File added: TEMP/NERF (copia) (copia)
File added: TEMP/NERF (8ª copia)
File added: TEMP/NERF (7ª copia)
File added: TEMP/NARF (copia)
File added: TEMP/NARF (otra copia)
File added: TEMP/NARF (4ª copia)
File added: TEMP/NERF
File added: TEMP/NARF (copia) (3ª copia)

As you can see, it work, the archive is ok too. This is a recursive function that can zip an entire folder. The only problem is that it doesn't create a empty folder.

Cheers.

少女的英雄梦 2024-07-19 13:54:35

下面是一些将整个目录压缩到 zip 文件中的代码。

这似乎可以在 Windows 和 Linux 上创建 zip 文件。 输出
文件似乎可以在 Windows 上正确提取(内置压缩文件夹功能,
WinZip 和 7-Zip) 和 Linux。 但是,zip 文件中会出现空目录
成为一个棘手的问题。 下面的解决方案似乎有效,但输出
Linux 上的“zipinfo”令人担忧。 另外目录权限也没有设置
正确地处理 zip 存档中的空目录。 这似乎需要
一些更深入的研究。

我从 此速度评论线程此 python 邮件列表线程

请注意,此函数旨在将文件放入 zip 存档中
要么没有父目录,要么只有一个父目录,所以它会修剪任何
文件系统路径中的前导目录,并且不将它们包含在
zip 存档路径。 当您只想获取一次时,通常会出现这种情况
目录并将其制作成可以在不同目录中解压的zip文件
地点。

关键字参数:

dirPath ——要归档的目录的字符串路径。 这是唯一的
必需的参数。 可以是绝对的也可以是相对的,但只能是一或零
主要目录将包含在 zip 存档中。

zipFilePath -- 输出 zip 文件的字符串路径。 这可以是绝对的
或相对路径。 如果 zip 文件已存在,则会更新该文件。 如果
不,它将被创建。 如果要从头替换,请将其删除
在调用此函数之前。 (默认计算为 dirPath + ".zip")

includeDirInZip -- 布尔值,指示顶级目录是否应该
包含在档案中或被省略。 (默认 True)

(请注意,StackOverflow 似乎无法使用以下命令漂亮地打印我的 python
三重引号字符串,所以我只是将我的文档字符串转换为此处的帖子文本)

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

def zipdir(dirPath=None, zipFilePath=None, includeDirInZip=True):

    if not zipFilePath:
        zipFilePath = dirPath + ".zip"
    if not os.path.isdir(dirPath):
        raise OSError("dirPath argument must point to a directory. "
            "'%s' does not." % dirPath)
    parentDir, dirToZip = os.path.split(dirPath)
    #Little nested function to prepare the proper archive path
    def trimPath(path):
        archivePath = path.replace(parentDir, "", 1)
        if parentDir:
            archivePath = archivePath.replace(os.path.sep, "", 1)
        if not includeDirInZip:
            archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1)
        return os.path.normcase(archivePath)

    outFile = zipfile.ZipFile(zipFilePath, "w",
        compression=zipfile.ZIP_DEFLATED)
    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        for fileName in fileNames:
            filePath = os.path.join(archiveDirPath, fileName)
            outFile.write(filePath, trimPath(filePath))
        #Make sure we get empty directories as well
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")
            #some web sites suggest doing
            #zipInfo.external_attr = 16
            #or
            #zipInfo.external_attr = 48
            #Here to allow for inserting an empty directory.  Still TBD/TODO.
            outFile.writestr(zipInfo, "")
    outFile.close()

这里有一些示例用法。 请注意,如果您的 dirPath 参数有多个前导目录,则默认情况下仅包含最后一个目录。 传递 includeDirInZip=False 以忽略所有前导目录。

zipdir("foo") #Just give it a dir and get a .zip file
zipdir("foo", "foo2.zip") #Get a .zip file with a specific file name
zipdir("foo", "foo3nodir.zip", False) #Omit the top level directory
zipdir("../test1/foo", "foo4nopardirs.zip")

Below is some code for zipping an entire directory into a zipfile.

This seems to work OK creating zip files on both windows and linux. The output
files seem to extract properly on windows (built-in Compressed Folders feature,
WinZip, and 7-Zip) and linux. However, empty directories in a zip file appear
to be a thorny issue. The solution below seems to work but the output of
"zipinfo" on linux is concerning. Also the directory permissions are not set
correctly for empty directories in the zip archive. This appears to require
some more in depth research.

I got some info from this velocity reviews thread and this python mailing list thread.

Note that this function is designed to put files in the zip archive with
either no parent directory or just one parent directory, so it will trim any
leading directories in the filesystem paths and not include them inside the
zip archive paths. This is generally the case when you want to just take a
directory and make it into a zip file that can be extracted in different
locations.

Keyword arguments:

dirPath -- string path to the directory to archive. This is the only
required argument. It can be absolute or relative, but only one or zero
leading directories will be included in the zip archive.

zipFilePath -- string path to the output zip file. This can be an absolute
or relative path. If the zip file already exists, it will be updated. If
not, it will be created. If you want to replace it from scratch, delete it
prior to calling this function. (default is computed as dirPath + ".zip")

includeDirInZip -- boolean indicating whether the top level directory should
be included in the archive or omitted. (default True)

(Note that StackOverflow seems to be failing to pretty print my python with
triple quoted strings, so I just converted my doc strings to the post text here)

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

def zipdir(dirPath=None, zipFilePath=None, includeDirInZip=True):

    if not zipFilePath:
        zipFilePath = dirPath + ".zip"
    if not os.path.isdir(dirPath):
        raise OSError("dirPath argument must point to a directory. "
            "'%s' does not." % dirPath)
    parentDir, dirToZip = os.path.split(dirPath)
    #Little nested function to prepare the proper archive path
    def trimPath(path):
        archivePath = path.replace(parentDir, "", 1)
        if parentDir:
            archivePath = archivePath.replace(os.path.sep, "", 1)
        if not includeDirInZip:
            archivePath = archivePath.replace(dirToZip + os.path.sep, "", 1)
        return os.path.normcase(archivePath)

    outFile = zipfile.ZipFile(zipFilePath, "w",
        compression=zipfile.ZIP_DEFLATED)
    for (archiveDirPath, dirNames, fileNames) in os.walk(dirPath):
        for fileName in fileNames:
            filePath = os.path.join(archiveDirPath, fileName)
            outFile.write(filePath, trimPath(filePath))
        #Make sure we get empty directories as well
        if not fileNames and not dirNames:
            zipInfo = zipfile.ZipInfo(trimPath(archiveDirPath) + "/")
            #some web sites suggest doing
            #zipInfo.external_attr = 16
            #or
            #zipInfo.external_attr = 48
            #Here to allow for inserting an empty directory.  Still TBD/TODO.
            outFile.writestr(zipInfo, "")
    outFile.close()

Here's some sample usages. Note that if your dirPath argument has several leading directories, only the LAST one will be included by default. Pass includeDirInZip=False to omit all leading directories.

zipdir("foo") #Just give it a dir and get a .zip file
zipdir("foo", "foo2.zip") #Get a .zip file with a specific file name
zipdir("foo", "foo3nodir.zip", False) #Omit the top level directory
zipdir("../test1/foo", "foo4nopardirs.zip")
感受沵的脚步 2024-07-19 13:54:35

对我来说最简单的方法是使用 zipfile CLI (命令-线路接口)。 zipfile CLI 可以将文件或文件夹作为参数,并将它们递归地添加到存档中。

因此,如果您的文件层次结构为:

- file1.txt
- folder1 
   - file2.txt
   - file3.txt

并且您希望将所有文件归档到“result.zip”中,您只需编写:

python -m zipfile -c result.zip file1.txt folder

如果您想在 python 代码中使用它并使用导入的 zipfile 模块,您可以调用它的主要功能如下:

import zipfile
zipfile.main(['-c', 'result.zip', 'file1.md', 'folder'])

Easiest way for me is using zipfile CLI (Command-Line Interface). The zipfile CLI can take either files or folders as arguments, and add them recursively to the archive.

So if you have a file hierarcy of:

- file1.txt
- folder1 
   - file2.txt
   - file3.txt

And you want all of it to be archived into 'result.zip', you simply write:

python -m zipfile -c result.zip file1.txt folder

In case you want to use it within python code and use the zipfile module imported, you can call its main function in the following way:

import zipfile
zipfile.main(['-c', 'result.zip', 'file1.md', 'folder'])
清风无影 2024-07-19 13:54:35

这是我用来压缩文件夹的函数:

import os
import os.path
import zipfile

def zip_dir(dirpath, zippath):
    fzip = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED)
    basedir = os.path.dirname(dirpath) + '/' 
    for root, dirs, files in os.walk(dirpath):
        if os.path.basename(root)[0] == '.':
            continue #skip hidden directories        
        dirname = root.replace(basedir, '')
        for f in files:
            if f[-1] == '~' or (f[0] == '.' and f != '.htaccess'):
                #skip backup files and all hidden files except .htaccess
                continue
            fzip.write(root + '/' + f, dirname + '/' + f)
    fzip.close()

here is my function i use to zip a folder:

import os
import os.path
import zipfile

def zip_dir(dirpath, zippath):
    fzip = zipfile.ZipFile(zippath, 'w', zipfile.ZIP_DEFLATED)
    basedir = os.path.dirname(dirpath) + '/' 
    for root, dirs, files in os.walk(dirpath):
        if os.path.basename(root)[0] == '.':
            continue #skip hidden directories        
        dirname = root.replace(basedir, '')
        for f in files:
            if f[-1] == '~' or (f[0] == '.' and f != '.htaccess'):
                #skip backup files and all hidden files except .htaccess
                continue
            fzip.write(root + '/' + f, dirname + '/' + f)
    fzip.close()
枕花眠 2024-07-19 13:54:35

如果您查看使用 Info-ZIP 创建的 zip 文件,您将看到确实列出了目录:

$ zip foo.zip -r foo
  adding: foo/ (stored 0%)
  adding: foo/foo.jpg (deflated 84%)
$ less foo.zip
  Archive:  foo.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
       0  Stored        0   0% 2013-08-18 14:32 00000000  foo/
  476320  Defl:N    77941  84% 2013-08-18 14:31 55a52268  foo/foo.jpg
--------          -------  ---                            -------
  476320            77941  84%                            2 files

请注意,目录条目的长度为零并且未压缩。 看来你可以通过按名称写入目录来使用 Python 实现相同的效果,但强制它不使用压缩。

if os.path.isdir(name):
    zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_STORED)
else:
    zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_DEFLATED)

确保 arcname/ 结尾可能是值得的。

If you look at a zip file created with Info-ZIP, you'll see that directories are indeed listed:

$ zip foo.zip -r foo
  adding: foo/ (stored 0%)
  adding: foo/foo.jpg (deflated 84%)
$ less foo.zip
  Archive:  foo.zip
 Length   Method    Size  Cmpr    Date    Time   CRC-32   Name
--------  ------  ------- ---- ---------- ----- --------  ----
       0  Stored        0   0% 2013-08-18 14:32 00000000  foo/
  476320  Defl:N    77941  84% 2013-08-18 14:31 55a52268  foo/foo.jpg
--------          -------  ---                            -------
  476320            77941  84%                            2 files

Notice that the directory entry has zero length and is not compressed. It seems you can achieve the same thing with Python by writing the directory by name, but forcing it to not use compression.

if os.path.isdir(name):
    zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_STORED)
else:
    zf.write(name, arcname=arcname, compress_type=zipfile.ZIP_DEFLATED)

It might be worth making sure arcname ends in a /.

走野 2024-07-19 13:54:35

添加一些导入后,您的代码对我来说运行良好,您如何调用脚本,也许您可​​以告诉我们“..\packed\bin”目录的文件夹结构。

我使用以下参数调用了您的代码:

planName='test.zip'
files=['z.py',]
folders=['c:\\temp']
(success,filename)=createZipFile(planName,files,folders)

`

after adding some imports your code runs fine for me, how do you call the script, maybe you could tell us the folder structure of the '..\packed\bin' directory.

I called your code with the following arguments:

planName='test.zip'
files=['z.py',]
folders=['c:\\temp']
(success,filename)=createZipFile(planName,files,folders)

`

初心 2024-07-19 13:54:35

这是我运行的编辑后的代码。 它基于上面的代码,取自邮件列表。 我添加了导入并创建了一个主例程。 我还删除了对输出文件名的修改,以使代码更短。

#!/usr/bin/env python

import os, zipfile, glob, sys

def addFolderToZip(myZipFile,folder):
    folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
    for file in glob.glob(folder+"/*"):
            if os.path.isfile(file):
                print file
                myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
            elif os.path.isdir(file):
                addFolderToZip(myZipFile,file)

def createZipFile(filename,files,folders):
    myZipFile = zipfile.ZipFile( filename, "w" ) # Open the zip file for writing 
    for file in files:
        file = file.encode('ascii') #convert path to ascii for ZipFile Method
        if os.path.isfile(file):
            (filepath, filename) = os.path.split(file)
            myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )

    for folder in  folders:   
        addFolderToZip(myZipFile,folder)  
    myZipFile.close()
    return (1,filename)

if __name__=="__main__":
    #put everything in sys.argv[1] in out.zip, skip files
    print createZipFile("out.zip", [], sys.argv[1])

在工作中,在我的 Windows 机器上,这段代码运行良好,但没有在 zip 文件中创建任何“文件夹”。 至少我记得是这样的。 现在在家里,在我的 Linux 机器上,创建的 zip 文件似乎很糟糕:

$ unzip -l out.zip 
Archive:  out.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of out.zip or
        out.zip.zip, and cannot find out.zip.ZIP, period.

我不知道是否我不小心破坏了代码,我认为它是一样的。 跨平台问题? 不管怎样,它与我原来的问题无关; 获取 zip 文件中的文件夹。 只是想发布我实际运行的代码,而不是我的代码所基于的代码。

Heres the edited code I ran. Its based on the code above, taken from the mailing list. I added the imports and made a main routine. I also cut out the fiddling with the output filename to make the code shorter.

#!/usr/bin/env python

import os, zipfile, glob, sys

def addFolderToZip(myZipFile,folder):
    folder = folder.encode('ascii') #convert path to ascii for ZipFile Method
    for file in glob.glob(folder+"/*"):
            if os.path.isfile(file):
                print file
                myZipFile.write(file, os.path.basename(file), zipfile.ZIP_DEFLATED)
            elif os.path.isdir(file):
                addFolderToZip(myZipFile,file)

def createZipFile(filename,files,folders):
    myZipFile = zipfile.ZipFile( filename, "w" ) # Open the zip file for writing 
    for file in files:
        file = file.encode('ascii') #convert path to ascii for ZipFile Method
        if os.path.isfile(file):
            (filepath, filename) = os.path.split(file)
            myZipFile.write( file, filename, zipfile.ZIP_DEFLATED )

    for folder in  folders:   
        addFolderToZip(myZipFile,folder)  
    myZipFile.close()
    return (1,filename)

if __name__=="__main__":
    #put everything in sys.argv[1] in out.zip, skip files
    print createZipFile("out.zip", [], sys.argv[1])

At work, on my Windows box, this code ran fine but didnt create any "folders" in the zipfile. At least I recall it did. Now at home, on my Linux box, the zip file created seems to be bad:

$ unzip -l out.zip 
Archive:  out.zip
  End-of-central-directory signature not found.  Either this file is not
  a zipfile, or it constitutes one disk of a multi-part archive.  In the
  latter case the central directory and zipfile comment will be found on
  the last disk(s) of this archive.
unzip:  cannot find zipfile directory in one of out.zip or
        out.zip.zip, and cannot find out.zip.ZIP, period.

I dont know if I accidently broke the code, I think its the same. Crossplatform issues? Either way, its not related to my original question; getting folders in the zip file. Just wanted to post the code I actually ran, not the code I based my code on.

与之呼应 2024-07-19 13:54:35

非常感谢您提供这个有用的功能! 我发现它非常有用,因为我也在寻求帮助。 但是,也许对其进行一点更改会很有用,

basedir = os.path.dirname(dirpath) + '/'

因为

basedir = os.path.dirname(dirpath + '/')

发现如果我想压缩位于“C:\folder\path\notWanted\to\zip\Example”的文件夹“Example”,

我进入了Windows:

dirpath = 'C:\folder\path\notWanted\to\zip\Example'
basedir = 'C:\folder\path\notWanted\to\zip\Example/'
dirname = 'C:\folder\path\notWanted\to\zip\Example\Example\Subfolder_etc'

但我想你的代码应该给出

dirpath = 'C:\folder\path\notWanted\to\zip\Example'
basedir = 'C:\folder\path\notWanted\to\zip\Example\'
dirname = '\Subfolder_etc'

Thank you wery much for this useful function! I found it very useful as I was also searching for help. However, maybe it would be useful to change it a little bit so that

basedir = os.path.dirname(dirpath) + '/'

would be

basedir = os.path.dirname(dirpath + '/')

Because found that if I want to zip folder 'Example' which is located at 'C:\folder\path\notWanted\to\zip\Example',

I got in Windows:

dirpath = 'C:\folder\path\notWanted\to\zip\Example'
basedir = 'C:\folder\path\notWanted\to\zip\Example/'
dirname = 'C:\folder\path\notWanted\to\zip\Example\Example\Subfolder_etc'

But I suppose your code should give

dirpath = 'C:\folder\path\notWanted\to\zip\Example'
basedir = 'C:\folder\path\notWanted\to\zip\Example\'
dirname = '\Subfolder_etc'
写下不归期 2024-07-19 13:54:35
import os
import zipfile

zf = zipfile.ZipFile("file.zip", "w")
for file in os.listdir(os.curdir):
    if not file.endswith('.zip') and os.path.isfile(os.curdir+'/'+file):
        print file
        zf.write(file)
    elif os.path.isdir(os.curdir+'/'+file):
        print f
        for f in os.listdir(os.curdir+'/'+file):
            zf.write(file+'\\'+f)
zf.close()
import os
import zipfile

zf = zipfile.ZipFile("file.zip", "w")
for file in os.listdir(os.curdir):
    if not file.endswith('.zip') and os.path.isfile(os.curdir+'/'+file):
        print file
        zf.write(file)
    elif os.path.isdir(os.curdir+'/'+file):
        print f
        for f in os.listdir(os.curdir+'/'+file):
            zf.write(file+'\\'+f)
zf.close()
咿呀咿呀哟 2024-07-19 13:54:35

当你想创建一个空文件夹时,你可以这样做:

    storage = api.Storage.open("empty_folder.zip","w")
    res = storage.open_resource("hannu//","w")
    storage.close()

文件夹在 winextractor 中不显示,但当你提取它时它会显示。

When you wanna create an empty folder, you can do it like this:

    storage = api.Storage.open("empty_folder.zip","w")
    res = storage.open_resource("hannu//","w")
    storage.close()

Folder not showe in winextractor, but when you extract it it is showed.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文