How to Get the Uncompressed and Compressed File Size of a File in Python



Python


In this article, we show how to get the uncompressed and compressed file size of a file in Python.

When referring to uncompressed and compressed file size, we are referrring to files within zip files.

The files within zip files are compressed. However, even though the files are compressed within zip files, we can find out the uncompressed file size and the compressed file size of each of the files within the zip file.

We do this using the zipfile module in Python.

This module allows us to work with zip files on our computer or within the internet directory being worked with.

With this module, we can find out the uncompressed and the compressed file size of each file in a zip file.

We show how to do this below.



So the first thing we need to do is import the zipfile module.

Again, this is the module that allows us to work and do functions on zip files.

We then create a variable, myzipfile, which is created to hold a zipfile object. This represents the zip file we are working with.

If you want to get the file size (uncompressed and compressed) of each file in the zip file, you can simply use the filelist property. This will tell us many things about each file, including the filename, the type of file compression that the file has been compressed with, the file mode, the uncompressed file size, and the compressed file size.

If you just want the file size of an individual file, then you can create another variable representative of that file and use the getinfo() function on the zipfile object, passing into this function the file you want to retrieve.

You then use the file_size attribute to get the uncompressed file size and the compress_size attribute to get the compressed file size.

We do this above with the 'Application.pdf' file.

We name the variable, applicationfile, and we see that the uncompressed size is 133050 bytes and the compressed file size is 83887 bytes.

And this is how we can either obtain the uncompressed and compressed file size of all the files within a zip file or just a single file within the zip file.


Related Resources

How to Create a Zip File in Python

How to Extract All Files and Folders from a Zip File in Python

How to Read the Contents of a Zip File in Python



HTML Comment Box is loading comments...