简体   繁体   English

从Python上的多个文件创建加密的Zip文件

[英]Create encrypted Zip file from multiple files on Python

I want to create an encrypted zip file which inlcudes 3 files. 我想创建一个包含3个文件的加密zip文件。

For now I have this solution which allows me to create an encrypted zip with only one file. 现在,我有了此解决方案,该解决方案使我可以仅使用一个文件来创建加密的zip。

loc_7z = r"C:\Program Files\7-Zip\7z.exe"

archive_command = r'"{}" a "{}" "{}"'.format(loc_7z, 'file.zip', 'file_name.xls')

subprocess.call(archive_command, shell=True)

When I try to pass a list of files as the third parameter it crashes. 当我尝试将文件列表作为第三个参数传递时,它崩溃了。

What format should the list of files have? 文件列表应采用哪种格式? I'm open to try different approaches as well. 我也愿意尝试其他方法。

Thank you. 谢谢。

The easy answer is to not use shell=True , and instead create a list of arguments. 简单的答案是不使用shell=True ,而是创建一个参数列表。 Then you can just stick the list of filenames onto that list of arguments. 然后,您可以将文件名列表粘贴到该参数列表上。 And you don't have to worry about quoting spaces or other funky characters in a way that works even if the filenames have quotes in them, etc. 而且,即使文件名中带有引号,您也不必担心以有效的方式引用空格或其他时髦字符。

def makezip(*files):
    loc_7z = r"C:\Program Files\7-Zip\7z.exe"
    archive_command = [loc_7z, 'file.zip', *files]
    subprocess.call(archive_command)

makezip('file_name.xls')
makezip('file name.xls')
makezip('file1.xls', 'file2.xls', 'file3.xls')
makezip(*big_old_list_of_files)

If you really must use shell=True for some reason, then you can't just turn the list of files into a string, you have to add each string to the end. 如果由于某种原因确实必须使用shell=True ,则不能仅将文件列表转换为字符串,而是必须将每个字符串添加到末尾。 Sort of like this: 有点像这样:

fileargs = ' '.join('"{}".format(file) for file in files)
archive_command = r'"{}" a "{}" {}'.format(loc_7z, 'file.zip', fileargs)

That's already pretty horrible—and making it work with proper quoting rules for Windows is even more horrible. 这已经非常可怕了,而使其与Windows的正确报价规则一起使用甚至更加可怕。 Just let subprocess do the work for you. 只需让subprocess为您完成工作即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM