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
print ('{:,.0f}'.format(os.path.getsize(filepath))+" B")
Kilobits
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<7))+" kb")
Kilobytes
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<10))+" KB")
Megabits
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<17))+" mb")
Megabytes
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<20))+" MB")
Gigabits
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<27))+" gb")
Gigabytes
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<30))+" GB")
Terabytes
print ('{:,.0f}'.format(os.path.getsize(filepath)/float(1<<40))+" TB")
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.
UPDATE USING PATHLIB
In reply to Hildy's comment, here's my suggestion for a compact pair of functions (keeping things 'atomic' rather than merging them) using just the Python standard library:
from pathlib import Path
def get_size(path = Path('.')):
""" Gets file size, or total directory size """
if path.is_file():
size = path.stat().st_size
elif path.is_dir():
size = sum(file.stat().st_size for file in path.glob('*.*'))
return size
def format_size(path, unit="MB"):
""" Converts integers to common size units used in computing """
bit_shift = {"B": 0,
"kb": 7,
"KB": 10,
"mb": 17,
"MB": 20,
"gb": 27,
"GB": 30,
"TB": 40,}
return "{:,.0f}".format(get_size(path) / float(1 << bit_shift[unit])) + " " + unit
# Tests and test results
>>> format_size("d:\\media\\bags of fun.avi")
'38 MB'
>>> format_size("d:\\media\\bags of fun.avi","KB")
'38,763 KB'
>>> format_size("d:\\media\\bags of fun.avi","kb")
'310,104 kb'