python zip&压缩多个文件

时间:2017-11-22 15:29:38

标签: python zip

我真的很抱歉成为那个新手,但我无法弄清楚为什么这不适用于我自己。 已经有类似的问题,但它们根本没有帮助。 我试着拉链&压缩目录中的不同文件。

这是我的代码:

import zipfile
import zlib

value_map =
['/home/shiva/Desktop/test2', 'None', False, False, True, False
['_MG_5290.JPG', '_MG_5294.JPG', '_MG_5293.JPG', '_MG_5295.JPG',
'_MG_5291.JPG', 'IMG_5434.JPG', '_MG_5292.JPG'], ['_MG_5298.CR2',
'_MG_5290.CR2', '_MG_5297.CR2', '_MG_5294.CR2', '_MG_5296.CR2',
'_MG_5291.CR2', '_MG_5292.CR2', '_MG_5299.CR2', '_MG_5293.CR2',
'_MG_5295.CR2']]

def compress(value_map):
    print "value_map:"
    print value_map

    try:
        compression = zipfile.ZIP_DEFLATED
        zf = zipfile.ZipFile(value_map[0] + "/RAWs.zip", mode="w")
        for x in value_map[7]:
            print "test1"  # prints
            zf.write(value_map[0] + x, compress_type=compression)  # nope
            print "test2"  # doesn't print
        zf.close()
        print ("[*] " + len(value_map[7]) + " have been moved to:")
        print ("[*] " + value_map[0] + "/RAWs.zip")
    except:
        print "[-] Couldn't compress\n[-] Exiting"
        sys.exit(0)

为什么???

1 个答案:

答案 0 :(得分:3)

以下是如何将zipfile包与压缩一起使用的示例。你的代码看起来几乎没问题。您的列表中有拼写错误!你不应该使用try&amp; amp;除非没有指定要捕获的错误!我除了FileNotFoundError之外,如果您要添加到zip的文件不存在,则会发生{。<}}。

示例(更新):

import zlib
import zipfile

def compress(file_names):
    print("File Paths:")
    print(file_names)

    path = "C:/data/"

    # Select the compression mode ZIP_DEFLATED for compression
    # or zipfile.ZIP_STORED to just store the file
    compression = zipfile.ZIP_DEFLATED

    # create the zip file first parameter path/name, second mode
    zf = zipfile.ZipFile("RAWs.zip", mode="w")
    try:
        for file_name in file_names:
            # Add file to the zip file
            # first parameter file to zip, second filename in zip
            zf.write(path + file_name, file_name, compress_type=compression)

    except FileNotFoundError:
        print("An error occurred")
    finally:
        # Don't forget to close the file!
        zf.close()


file_names= ["test_file.txt", "test_file2.txt"]
compress(file_names)