Search

Understanding and Converting File Sizes (Bytes, KB, MB, GB, PB)

Most times we want to understand what file sizes our data has. For example, when the file sizes are stated in bytes, we would want to understand what are the stated unit is in kilobytes, or gigabytes etc. Well, this can easily be coded in python.

python file sizes

 

But first, what are file sizes?

A Files size is a measure of how much data a computer file contains, or alternatively, the measure of the storage in memory it consumes. All file size units have the byte as the unit of measurement and all other units are derived from the byte.

A byte is a sequence of 8 bits processed as a single unit of information. A byte is enough to represent one unit of information. A bit is either an ‘on’ or ‘off’ position in the computer memory where “on” is represented by a ‘1’ and an “off” as ‘0’. So a byte contains 8 of such 1s and 0s. The computer processes our information as bytes.

In python, characters in strings are stored as one byte although extra bytes are allocated for storing any character so if you call sys.getsizeof(char) you may get more than one byte.

Larger bytes can be subdivided further into kilobytes, megabytes, gigabytes, terabytes, petabytes etc. The table below shows the different file units and their comparisons.

1024 bytes 1 KB
1024 KB 1 MB
1024 MB 1 GB
1024 GB 1 TB
1024 TB 1 PB

Where KB means kilobytes, MB means megabytes, GB means gigabytes, TB means terabytes and PB means petabytes.

Using the metrics above, given any number of bytes we can convert to other metric units.

I wrote a little program below that does just that. Given any number of bytes, it can convert the byte measure into larger sizes provided it is possible.

I hope you do enjoy it. I wrote it based on a request from a friend.

Happy pythoning.

No comments:

Post a Comment

Your comments here!

Matched content