我需要创建一个临时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文件的工具。这种“双重加密层”是客户的需求,虽然我并不认为有必要,但我没有权力将其从项目中删除。
我不习惯处理临时文件。我做错什么了?在
使用tempfile-模块可以创建临时文件,这些文件在关闭或离开{a2}-块时自动删除。使用pyminizip-模块可以获得加密的zip文件。在
pyminizip.compress
将生成的zip文件的保存路径作为第三个参数。如果文件已经存在,则尝试覆盖它。当前代码使用对tempfile(tmp
)的引用,这将导致观察到的错误消息:错误的直接原因是使用了引用本身而不是其文件名,也就是说,为了避免错误,实际上应该使用}。但是,如果改变了这一点,则会生成一个不同的错误消息,即
^{pr2}$tmp.name
,而不是{这是因为pyminizip模块试图在tempfile仍处于打开状态时删除它。如果之前关闭了tempfile,它将被覆盖而不显示错误消息。但是,这只会创建一个普通文件,而不是临时文件,也就是说,当关闭或离开
with
-块时,文件不会被自动删除。在因此,以这种方式使用tempfile和pyminizip模块创建临时加密的zip文件是不可能的。但是,tempfile模块允许创建临时文件以及临时目录。{temporary directories,Like a temporary files^被删除时,{。如果删除临时目录,则其中包含的文件也将被删除。因此,另一种选择是普通的加密zip文件(使用pyminizip模块创建),它们存储在临时文件夹(使用tempfile模块创建)中:
如果
with
-块仍然存在,则临时目录及其包含的任何加密zip文件都将被删除。在顺便说一下:
pyminizip.compress
不支持with
-语句。这将导致错误消息:AttributeError: __enter__
。在当前代码中,您无法看到此错误消息,因为已发布的错误消息是在之前触发的。在相关问题 更多 >
编程相关推荐