0

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.

1 Answer 1

1

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.

1
  • Thank you for the answer! I end up using subprocess but on a different way. archive_command = [loc_7z, 'a', 'file.zip', '-ppassword'] + list_files and then calling it.
    – AlexSB
    Commented Aug 15, 2018 at 10:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.