Python - Extracting a single file from a zipfile














































Python - Extracting a single file from a zipfile



In this article, we are going to learn how to extract a single file from zip file using python.

CODE:
import zipfile

my_zipfile = zipfile.ZipFile('CPP_demo.zip''r')

my_zipfile.extract("CPP_demo.txt")

my_zipfile.close()

OUTPUT:
Only CPP_demo.txt was extracted from the zip file.


Code Explanation:

 i. We have to import zipfile first.

 ii. zipfile.ZipFile will open the zip file and inside this class, you have to pass the name of the zip file that you want to open and then mode.

 iii. In mode, we have to pass r because we are extracting the specific file, which is basically reading. Here we extracted CPP_demo.txt from the zip file.

 iv. Now you have to close the zip file. We must call close() before exiting our program or essential records will not be written.


Comments