在Python中解压缩文件

我通过zipfile模块文档阅读,但不明白如何解压缩文件,只有如何压缩文件。 如何将zip文件的所有内容解压到同一目录中?

import zipfile zip_ref = zipfile.ZipFile(path_to_zip_file, 'r') zip_ref.extractall(directory_to_extract_to) zip_ref.close() 

这是非常多的!

如果您使用Python 3.2或更高版本:

 import zipfile with zipfile.ZipFile("file.zip","r") as zip_ref: zip_ref.extractall("targetdir") 

因为它使用上下文pipe理器构造,所以不需要使用close或try / catch

如果你使用的是Python 2.6+,使用extractall方法

 zip = ZipFile('file.zip') zip.extractall()