In this section, we are going to work with ZIP files. We will learn about the zipfile module of python, how to create ZIP files, how to test whether an entered filename is a valid zip filename or not, reading the metadata, and so on.
First, we will learn how to create a zip file using the make_archive() function of the shutil module. Create a script called make_zip_file.py and write the following code in it:
import shutil
shutil.make_archive('work', 'zip', 'work')
Run the script as follows:
student@ubuntu:~$ python3 make_zip_file.py
Now check your current working directory and you will see work.zip.
Now, we will test whether the entered filename is a zip file or not. For this purpose, the zipfile module has the is_zipfile() function.
Create a script called check_zip_file.py and write the following content in it:
import zipfile
for f_name in ['hello.py', 'work.zip', 'welcome.py', 'sample.txt', 'test.zip']:
try:
print('{:} {}'.format(f_name, zipfile.is_zipfile(f_name)))
except IOError as err:
print('{:} {}'.format(f_name, err))
Run the script as follows:
student@ubuntu:~$ python3 check_zip_file.py
Output :
hello.py False
work.zip True
welcome.py False
sample.txt False
test.zip True
In this example, we have used a for loop, where we are checking the filenames in a list. The is_zipfile() function will check, one by one, the filenames and will give Boolean values as a result.
Now, we will see how we can read the metadata from an archived ZIP file using the zipfile module of Python. Create a script called read_metadata.py and write the following content in it:
import zipfile
def meta_info(names):
with zipfile.ZipFile(names) as zf:
for info in zf.infolist():
print(info.filename)
if info.create_system == 0:
system = 'Windows'
elif info.create_system == 3:
system = 'Unix'
else:
system = 'UNKNOWN'
print("System :", system)
print("Zip Version :", info.create_version)
print("Compressed :", info.compress_size, 'bytes')
print("Uncompressed :", info.file_size, 'bytes')
print()
if __name__ == '__main__':
meta_info('work.zip')
Execute the script as follows:
student@ubuntu:~$ python3 read_metadata.py
Output:
sample.txt
System : Unix
Zip Version : 20
Compressed : 2 bytes
Uncompressed : 0 bytes
bye.py
System : Unix
Zip Version : 20
Compressed : 32 bytes
Uncompressed : 30 bytes
extract_contents.py
System : Unix
Zip Version : 20
Compressed : 95 bytes
Uncompressed : 132 bytes
shutil_make_archive.py
System : Unix
Zip Version : 20
Compressed : 160 bytes
Uncompressed : 243 bytes
To get the metadata information about the zip file, we used the infolist() method of the ZipFile class.