I am using a library that reads a file and returns its size in bytes.
This file size is then displayed to the end user; to make it easier for them to understand it, I am explicitly converting the file size to MB
by dividing it by 1024.0 * 1024.0
. Of course this works, but I am wondering is there a better way to do this in Python?
By better, I mean perhaps a stdlib function that can manipulate sizes according to the type I want. Like if I specify MB
, it automatically divides it by 1024.0 * 1024.0
. Somethign on these lines.
I'm new to programming. I came up with this following function that converts a given file size into readable format.
Here's a version that matches the output of ls -lh.
See below for a quick and relatively easy-to-read way to print file sizes in a single line of code if you already know what you want. These one-liners combine the great answer by @ccpizza above with some handy formatting tricks I read here How to print number with commas as thousands separators?.
Bytes
Kilobits
Kilobytes
Megabits
Megabytes
Gigabits
Gigabytes
Terabytes
Obviously they assume you know roughly what size you're going to be dealing with at the outset, which in my case (video editor at South West London TV) is MB and occasionally GB for video clips.
In reply to Hildy's comment, here's my suggestion for a compact (3 line) function using just the Python standard library:
This work correctly for all file sizes:
Similar to Aaron Duke's reply but more "pythonic" ;)
Instead of a size divisor of
1024 * 1024
you could use the<<
bitwise shifting operator, i.e.1<<20
to get megabytes,1<<30
to get gigabytes, etc.I defined a constant
MBFACTOR = float(1<<20)
which can then be used with bytes, i.e.:megas = size_in_bytes/MBFACTOR
.