Skip to content Skip to sidebar Skip to footer

Encrypt Folder Or Zip File Using Python

So I am trying to encrypt a directory using python and I'm not sure what the best way to do that is. I am easily able to turn the folder into a zip file, but from there I have trie

Solution 1:

I still recommend 7-zip.

let's say you want to name the zip folder as myzip.zip

Import subprocesszp= subprocess.call(['7z', 'a', 'your password', '-y', 'myzip.zip'] + ['your file'])

An alternative way:

Import pyminzip
level=4 #level of compression
pyminizip.compress("your file", "myzip.zip", "your password", level)

Solution 2:

Using 7-Zip through the subprocess module works. Here are some issues I encountered and had to resolve: You need to specify the path to 7zip separate from the cmd variable in the Popen subprocess, and build the command with variables rather than a solid string:

appPath="C:\Program Files\\7-Zip"
zApp="7z.exe"
zAction='a'
zPass='-pPASSWORD'
zAnswer='-y'
zDir=directoryToZip
progDir=os.path.join(appPath,zApp)

cmd = [zApp, zAction, zipFileName, zPass, zAnswer, zDir]
subprocess.Popen(cmd, executable=progDir, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)

That will create a zip file (in the location with the name in the zipFileName variable), including the contents (directories and files) inside the "directoryToZip" path

progDir has to be specified for separate from the application you are calling as part of the Open command (this is the executable path), and the command string needed to be built out as variables to deal with the windows backslash escaping setup.

Post a Comment for "Encrypt Folder Or Zip File Using Python"