How to get the list of all files in a zip archive

Python : How to get the list of all files in a zip archive

How to get the list of all files in a zip archive in Python

In this article we will learn about various ways to get detail about all files in a zip archive like file’s name, size etc.

How to find name of all the files in the ZIP archive using ZipFile.namelist() :

ZipFile class from zipfile module provide a member function i.e. ZipFile.namelist() to get the names of all files present it.

from zipfile import ZipFile
def main():
    # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
       # To get list of files names in zip
       fileslist = zip_Obj.namelist()
       # Iterate over the fileslist names in given list & print them
       for ele in fileslist:
           print(ele)
if __name__ == '__main__':
    main()
Output :
DocumentDir/doc1.csv
DocumentDir/doc2.csv
DocumentDir/test.csv

Find detail info like name, size etc of the files in a Zip file using ZipFile.infolist() :

ZipFile class from zipfile module also provide a member function i.e. ZipFile.infolist() to get the details of each entries present in zipfile.

Here a list of ZipInfo objects is returned where each object has certain information like name, permission, size etc.

from zipfile import ZipFile
def main():
        # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
        # Get list of ZipInfo objects
        fileslist = zip_Obj.infolist()
        # Iterate of over object’s list and also to access members of the object
        for ele in fileslist:
            print(ele.filename, ' : ', ele.file_size, ' : ', ele.date_time, ' : ', ele.compress_size)
if __name__ == '__main__':
    main()
Output :
DocumentDir/doc1.csv :  2759  :  (2021, 01, 03, 21, 00, 02)  :  2759
DocumentDir/doc2.csv :  2856  :  (2021, 01, 25, 13, 45, 58)  :  2856
DocumentDir/test.csv  :  3458  :  (2021, 02, 20, 20, 20, 41)  :  3458

Details of ZIP archive to std.out using ZipFile.printdir() :

ZipFile class from zipfile module also provide a member function i.e. ZipFile.printdir() which can print the contents of zip file as table.

from zipfile import ZipFile
def main():
    # To Create a ZipFile Object and load Document.zip in it
    with ZipFile('DocumentDir.zip', 'r') as zip_Obj:
        zip_Obj.printdir()
if __name__ == '__main__':
    main()
Output :
File Name                                             Modified                         Size
DocumentDir/doc1.csv                      2021-01-03 21:00:02         2759
DocumentDir/doc2.csv                      2021-01-25 13:45:58         2856
DocumentDir/test.csv                        2021-02-20 20:20:41         3458