Skip to content

Python zipfile extract single file

  • by

use ZipFile.extractall() method to zipfile extract a single file in Python. This method takes a path, members, pwd as an argument and extracts all the contents.

Python ZipFile class provides a member function to extract a single from a ZIP File.

ZipFile.extract(member, path=None, pwd=None)

Python zipfile extracts a single file

A simple example code extracts the single file from the zip file. If the filenames have the .py extension, they will extract them inside the temp_py folder. Otherwise, it won’t extract the files.

from zipfile import ZipFile

with ZipFile('modules\\stuff.zip', 'r') as zipObject:
    listOfFileNames = zipObject.namelist()
    for fileName in listOfFileNames:
        if fileName.endswith('.py'):
            # Extract a single file from zip
            zipObject.extract(fileName, 'temp_py')
            print('All the python files are extracted')

Output:

Python zipfile extracts a single file

Do comment if you have any doubts or suggestions on this Python zipfile topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading