zip文件并避免目录结构

时间:2015-01-16 19:52:32

标签: python zip

我有一个Python脚本来压缩文件(new.txt)。

tofile =  "/root/files/result/"+file
targetzipfile = new.zip   # This is how I want my zip to look like
zf = zipfile.ZipFile(targetzipfile, mode='w')
try:
    #adding to archive
    zf.write(tofile)
finally:
    zf.close()

当我这样做时,我得到了zip文件。但是当我尝试解压缩文件时,我得到了与文件路径对应的一系列目录中的文本文件,即我在root目录中看到一个名为result的文件夹,其中包含更多目录,即我有

/root/files/result/new.zip

当我解压缩new.zip时,我有一个类似于

的目录结构
/root/files/result/root/files/result/new.txt.

有没有一种方法可以拉链,当我解压缩时我只得到new.txt

换句话说,我有/root/files/result/new.zip,当我解压缩new.zip时,它应该看起来像

/root/files/results/new.txt

10 个答案:

答案 0 :(得分:27)

zipfile.write()方法采用可选的arcname参数,该参数指定zipfile中文件的名称

我认为您需要对目标进行修改,否则会复制目录。使用:arcname来避免它。试试这样:

import os
import zipfile

def zip(src, dst):
    zf = zipfile.ZipFile("%s.zip" % (dst), "w", zipfile.ZIP_DEFLATED)
    abs_src = os.path.abspath(src)
    for dirname, subdirs, files in os.walk(src):
        for filename in files:
            absname = os.path.abspath(os.path.join(dirname, filename))
            arcname = absname[len(abs_src) + 1:]
            print 'zipping %s as %s' % (os.path.join(dirname, filename),
                                        arcname)
            zf.write(absname, arcname)
    zf.close()

zip("src", "dst")

答案 1 :(得分:6)

zf.write(tofile)

改变

zf.write(tofile, zipfile_dir)

例如

zf.write("/root/files/result/root/files/result/new.txt", "/root/files/results/new.txt")

答案 2 :(得分:4)

查看 Zipfile.write 的文档。

  

ZipFile.write(filename [,arcname [,compress_type]])写入文件   命名归档文件的文件名,给它归档名称arcname(by   默认情况下,这与文件名相同,但没有驱动器号   并删除了前导路径分隔符

https://docs.python.org/2/library/zipfile.html#zipfile.ZipFile.write

尝试以下方法:

import zipfile
import os
filename = 'foo.txt'

# Using os.path.join is better than using '/' it is OS agnostic
path = os.path.join(os.path.sep, 'tmp', 'bar', 'baz', filename)
zip_filename = os.path.splitext(filename)[0] + '.zip'
zip_path = os.path.join(os.path.dirname(path), zip_filename)

# If you need exception handling wrap this in a try/except block
with zipfile.ZipFile(zip_path, 'w') as zf:
    zf.write(path, zip_filename)

最重要的是,如果您不提供存档名称,那么文件名将用作存档名称,它将包含文件的完整路径。

答案 3 :(得分:3)

您可以使用以下方法隔离源文件的文件名:

name_file_only= name_full_path.split(os.sep)[-1]

例如,如果name_full_path/root/files/results/myfile.txt,则name_file_only将是myfile.txt。要将myfile.txt压缩到存档zf的根目录中,可以使用:

zf.write(name_full_path, name_file_only)

答案 4 :(得分:2)

最清楚地说明,

目录结构:

/Users
 └── /user
 .    ├── /pixmaps
 .    │    ├── pixmap_00.raw
 .    │    ├── pixmap_01.raw
      │    ├── /jpeg
      │    │    ├── pixmap_00.jpg
      │    │    └── pixmap_01.jpg
      │    └── /png
      │         ├── pixmap_00.png
      │         └── pixmap_01.png
      ├── /docs
      ├── /programs
      ├── /misc
      .
      .
      .

感兴趣的目录: / Users / user / pixmaps

首先尝试

import os
import zipfile

TARGET_DIRECTORY = "/Users/user/pixmaps"
ZIPFILE_NAME = "CompressedDir.zip"

def zip_dir(directory, zipname):
    """
    Compress a directory (ZIP file).
    """
    if os.path.exists(directory):
        outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)

        for dirpath, dirnames, filenames in os.walk(directory):
            for filename in filenames:

                filepath   = os.path.join(dirpath, filename)
                outZipFile.write(filepath)

        outZipFile.close()




if __name__ == '__main__':
    zip_dir(TARGET_DIRECTORY, ZIPFILE_NAME)

ZIP文件结构:

CompressedDir.zip
.
└── /Users
     └── /user
          └── /pixmaps
               ├── pixmap_00.raw
               ├── pixmap_01.raw
               ├── /jpeg
               │    ├── pixmap_00.jpg
               │    └── pixmap_01.jpg
               └── /png
                    ├── pixmap_00.png
                    └── pixmap_01.png

避免使用完整的目录路径

def zip_dir(directory, zipname):
    """
    Compress a directory (ZIP file).
    """
    if os.path.exists(directory):
        outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)

        # The root directory within the ZIP file.
        rootdir = os.path.basename(directory)

        for dirpath, dirnames, filenames in os.walk(directory):
            for filename in filenames:

                # Write the file named filename to the archive,
                # giving it the archive name 'arcname'.
                filepath   = os.path.join(dirpath, filename)
                parentpath = os.path.relpath(filepath, directory)
                arcname    = os.path.join(rootdir, parentpath)

                outZipFile.write(filepath, arcname)

    outZipFile.close()




if __name__ == '__main__':
    zip_dir(TARGET_DIRECTORY, ZIPFILE_NAME)

ZIP文件结构:

CompressedDir.zip
.
└── /pixmaps
     ├── pixmap_00.raw
     ├── pixmap_01.raw
     ├── /jpeg
     │    ├── pixmap_00.jpg
     │    └── pixmap_01.jpg
     └── /png
          ├── pixmap_00.png
          └── pixmap_01.png

答案 5 :(得分:1)

write方法中的arcname参数指定zipfile中文件的名称:

import os
import zipfile

# 1. Create a zip file which we will write files to
zip_file = "/home/username/test.zip"
zipf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)

# 2. Write files found in "/home/username/files/" to the test.zip
files_to_zip = "/home/username/files/"
for file_to_zip in os.listdir(files_to_zip):

    file_to_zip_full_path = os.path.join(files_to_zip, file_to_zip)

    # arcname argument specifies what will be the name of the file inside the zipfile
    zipf.write(filename=file_to_zip_full_path, arcname=file_to_zip)

zipf.close()

答案 6 :(得分:1)

我们可以使用这个

{{1}}

对我来说,这有效。

答案 7 :(得分:1)

最后它比预期的简单,我使用参数“arcname”将模块配置为“file_to_be_zipped.txt”,因此文件夹不会出现在我的最终压缩文件中:

mmpk_zip_file = zipfile.ZipFile("c:\\Destination_folder_name\newzippedfilename.zip", mode='w', compression=zipfile.ZIP_DEFLATED)
mmpk_zip_file.write("c:\\Source_folder_name\file_to_be_zipped.txt", "file_to_be_zipped.txt")
mmpk_zip_file.close()

答案 8 :(得分:0)

我面临同样的问题,我用writestr解决了这个问题。您可以像这样使用它:

zipObject.writestr(<filename> , <file data, bytes or string>)

答案 9 :(得分:0)

如果您想用一种优雅的方式来pathlib进行操作,可以按以下方式使用它:

from pathlib import Path
import zipfile

def zip_dir(path_to_zip: Path):
    zip_file = Path(path_to_zip).with_suffix('.zip')
    z = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
    for f in list(path_to_zip.rglob('*.*')):
        z.write(f, arcname=f.relative_to(path_to_zip))