Use subprocess python library to unzip a file using 7zip

守給你的承諾、 提交于 2020-12-14 06:51:38

问题


I would like to unzip a file with Python using 7zip executable. In Perl this is pretty straightforward:

$zip_exe_path = "C:\\Dropbox\\7-zip\\7z.exe";
$logfile_path = "C:\\Temp\\zipped_file.7z";
system ("$zip_exe_path x $log_file_path -y");

I tried this:

import subprocess
zip_exe_path = "C:\\Dropbox\\7-zip\\7z.exe"
logfile_path = "C:\\Temp\\zipped_file.7z"
subprocess.call(['zip_exe_path','x','logfile_path','-y'])

When I do so I get this error:

FileNotFoundError: [WinError 2] The system cannot find the file specified

Thanks for any help!


回答1:


The error is that you are passing the strings 'zip_exe_path' and 'logfile_path' instead of the values of those variables.

import subprocess
zip_exe_path = "C:\\Dropbox\\7-zip\\7z.exe"
logfile_path = "C:\\Temp\\zipped_file.7z"
subprocess.call([zip_exe_path, 'x', logfile_path, '-y'])

You can of course pass the command as a single string with shell=True but the shell does not add any value and incurs some overhead (and risk!)




回答2:


Why not use python zip:

import zipfile

with zipfile.ZipFile(logfile_path, 'r') as z:
    z.extractall()

Or using subprocess:

subprocess.call(['zip_exe_path','x','logfile_path','-y'], shell=True)



回答3:


This work like a charm for me :)

first, install py7zr library:

pip install py7zr

for extracting all files in .7z:

from py7zr import py7zr

with py7zr.SevenZipFile('7z file_location', mode='r') as z:
    z.extractall()

for extracting a single file:

from py7zr import py7zr

with py7zr.SevenZipFile('7z file_location', mode='r') as z:
    z.extract(targets=['rootdir/filename'])



回答4:


Figured it out:

import subprocess

subprocess.Popen(zip_exe+' x '+file+' -o'+output_loc,stdout=subprocess.PIPE)


来源:https://stackoverflow.com/questions/35754898/use-subprocess-python-library-to-unzip-a-file-using-7zip

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!