Tutorial Example

Fix Python ZipFile AttributeError: ‘str’ object has no attribute ‘fp’ – Python Tutorial

We can use python ZipFile class to extract files from a zip file, here is the tutorial:

Python Extract ZIP Files: A Step Guide – Python Tutorial

However, you may get AttributeError: ‘str’ object has no attribute ‘fp’ when using it. In this tutorial, we will introduce you how to fix this error.

For example:

import zipfile

file_zip_name = r'F:\github-jupyter\Azure\MachineLearningNotebooks.zip'

try:
    with zipfile.ZipFile.open(file_zip_name, "r") as f:
        f.extractall("F:\\")
except Exception as e:
    print(e)

Run this code, you will get this error: AttributeError: ‘str’ object has no attribute ‘fp’

How to fix this AttributeError?

We should use zipfile.ZipFile() not zipfile.ZipFile().open().

try:
    with zipfile.ZipFile(file_zip_name, "r") as f:
        f.extractall("F:\\")
except Exception as e:
    print(e)

Run this code, you will see this AttributeError is fixed.