如何使用pyminizip在python3.x中创建临时ZIP?

2024-05-13 01:48:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个临时zip文件来存储文件。该ZIP文件需要加密,因此zipfile在这里不会起作用。该文件将被进一步加密(ZIP将再次加密到另一个文件中),因此压缩文件被用作减小文件大小的一种方法,以便更快地进行互联网传输,以及第一层加密。 到目前为止,我得到的是:

import getpass
import tempfile
import pyminizip

def ZipFunction():
    #This zips the file and encrypts it with a password
    filename = input('Enter the file name: ')
    passkey = getpass.getpass(prompt='Enter the password for the file: ')
    passkey2 = getpass.getpass(prompt='Confirm the password: ')
    if passkey != passkey2:
        print('The passwords must be the same! Please restart the process.')
        exit()
    else:
        #Here's where I need help
        with tempfile.TemporaryFile() as tmp:
            with pyminizip.compress(filename,None,tmp,passkey,9) as archive:
                zipstring = archive.readlines()

        #From here on the zipstring var is encrypted and creates the "further encrypted"
        #file. From here on the script works normally

返回的错误是ValueError: expected arguments are compress(src, srcpath, dst, pass, level)。 我愿意将pyminizip更改为另一个可以创建加密zip文件的工具。这种“双重加密层”是客户的需求,虽然我并不认为有必要,但我没有权力将其从项目中删除。 我不习惯处理临时文件。我做错什么了?在


Tags: and文件theimportwithpasswordzipfilename
1条回答
网友
1楼 · 发布于 2024-05-13 01:48:48

使用tempfile-模块可以创建临时文件,这些文件在关闭或离开{a2}-块时自动删除。使用pyminizip-模块可以获得加密的zip文件。在

pyminizip.compress将生成的zip文件的保存路径作为第三个参数。如果文件已经存在,则尝试覆盖它。当前代码使用对tempfile(tmp)的引用,这将导致观察到的错误消息:

ValueError: expected arguments are compress(src, srcpath, dst, pass, level) 

错误的直接原因是使用了引用本身而不是其文件名,也就是说,为了避免错误,实际上应该使用tmp.name,而不是{}。但是,如果改变了这一点,则会生成一个不同的错误消息,即

^{pr2}$

这是因为pyminizip模块试图在tempfile仍处于打开状态时删除它。如果之前关闭了tempfile,它将被覆盖而不显示错误消息。但是,这只会创建一个普通文件,而不是临时文件,也就是说,当关闭或离开with-块时,文件不会被自动删除。在

因此,以这种方式使用tempfile和pyminizip模块创建临时加密的zip文件是不可能的。但是,tempfile模块允许创建临时文件以及临时目录。{temporary directories,Like a temporary files^被删除时,{。如果删除临时目录,则其中包含的文件也将被删除。因此,另一种选择是普通的加密zip文件(使用pyminizip模块创建),它们存储在临时文件夹(使用tempfile模块创建)中:

...
with tempfile.TemporaryDirectory() as tdir:
    sourceFile = <path to file to be zipped>
    destinationFile = "destFile.zip"
    password = "whatever"
    compression_level = 9 # 1-9
    pyminizip.compress(sourceFile, None, tdir + "\\" + destinationFile, password, compression_level)

    # inside with-block: temp-directory and contained encrypted zip-files exist
    ...                     

# outside with-block: temp-directory and contained encrypted zip-files deleted
...                     

如果with-块仍然存在,则临时目录及其包含的任何加密zip文件都将被删除。在

顺便说一下:pyminizip.compress不支持with-语句。这将导致错误消息:AttributeError: __enter__。在当前代码中,您无法看到此错误消息,因为已发布的错误消息是在之前触发的。在

相关问题 更多 >