How to extract all the .txt files from a zip file using Python?

PythonServer Side ProgrammingProgramming

In order to extract all .txt files from a zip, you'll need to loop over all files in the zipfile, check if a file is txt file or not. If it is a txt file then extract it. For this we'll use the zipfile module and its extract function.

For example

import zipfile
my_zip = zipfile.Zipfile('my_zip_file.zip') # Specify your zip file's name here
storage_path = '.'
for file in my_zip.namelist():
    if my_zip.getinfo(file).filename.endswith('.txt'):
        my_zip.extract(file, storage_path) # extract the file to current folder if it is a text file

Running the above code will open the my_zip_file.zip and extract all txt files from it and store them in the current directory.

raja
Published on 28-Dec-2017 11:22:14
Advertisements