简体   繁体   中英

Create encrypted Zip file from multiple files on Python

I want to create an encrypted zip file which inlcudes 3 files.

For now I have this solution which allows me to create an encrypted zip with only one file.

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. 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. 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. Just let subprocess do the work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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