是否有一個簡單的Python功能,將允許解壓的.zip文件,像這樣?:如何在所有操作系統上使用Python解壓縮文件?
unzip(ZipSource, DestinationDirectory)
我需要的解決方案,採取同樣在Windows,Mac和Linux:總是產生一個文件,如果拉鍊是一個文件,目錄如果zip是一個目錄,並且目錄如果zip是多個文件;總是在裏面,而不是在給定的目的地目錄
如何在Python中解壓文件?
是否有一個簡單的Python功能,將允許解壓的.zip文件,像這樣?:如何在所有操作系統上使用Python解壓縮文件?
unzip(ZipSource, DestinationDirectory)
我需要的解決方案,採取同樣在Windows,Mac和Linux:總是產生一個文件,如果拉鍊是一個文件,目錄如果zip是一個目錄,並且目錄如果zip是多個文件;總是在裏面,而不是在給定的目的地目錄
如何在Python中解壓文件?
使用zipfile
模塊中的標準庫:
import zipfile,os.path
def unzip(source_filename, dest_dir):
with zipfile.ZipFile(source_filename) as zf:
for member in zf.infolist():
# Path traversal defense copied from
# http://hg.python.org/cpython/file/tip/Lib/http/server.py#l789
words = member.filename.split('/')
path = dest_dir
for word in words[:-1]:
while True:
drive, word = os.path.splitdrive(word)
head, word = os.path.split(word)
if not drive:
break
if word in (os.curdir, os.pardir, ''):
continue
path = os.path.join(path, word)
zf.extract(member, path)
注意,使用extractall
將是短了很多,但是這方法確實不的Python 2.7.4之前防止path traversal vulnerabilities。如果你可以保證你的代碼在最新版本的Python上運行。
Python 3.x都有使用-e參數,不能是-h ..如:
python -m zipfile -e compressedfile.zip c:\output_folder
參數如下..
zipfile.py -l zipfile.zip # Show listing of a zipfile
zipfile.py -t zipfile.zip # Test if a zipfile is valid
zipfile.py -e zipfile.zip target # Extract zipfile into target dir
zipfile.py -c zipfile.zip src ... # Create zipfile from sources
會脆弱的zip文件必須專門設立對於一次攻擊,還是僅僅是不良習慣的結果? – tkbx
@tkbx:兩者都是可能的。例如。與絕對路徑名。 –
在這種情況下,extractall()沒有這個問題的替代方案是什麼?這個問題發生在使用pwd作爲/的zip文件時? – tkbx