How to Get File Size using Python in Bytes/KB/MB or GB

We can easily get the size of a file using Python by making use of the os.path.getsize function.


import os

filename = 'data.csv'
filesize = os.path.getsize(filename)

filesize_in_kb = filesize / 1024
filesize_in_mb = filesize_in_kb / 1024
filesize_in_gb = filesize_in_mb / 1024

print(f"File Name: {filename}")
print(f"File Size in bytes: {filesize}")
print(f"File size in KB: {filesize_in_kb:.2f} KB")
print(f"File size in MB: {filesize_in_mb:.2f} MB")
print(f"File size in GB: {filesize_in_gb:.2f} GB")


File Name: data.csv
File Size in bytes: 10377990
File size in KB: 10134.76 KB
File size in MB: 9.90 MB
File size in GB: 0.01 GB
Get File Size in Python - Bytes KB MB or GB

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap