Get File Size in Bytes, Kb, Mb, And Gb using Python
Handling file sizes in Python is a common task, especially when working with data processing, file management, or simply understanding resource usage. Fortunately, Python provides several methods to obtain file sizes in various units, such as bytes, kilobytes, megabytes, and gigabytes. In this article, we will explore five simple and generally used methods to achieve this.
Get File Size In Python In Bytes, Kb, Mb, And Gb
Below, are the methods to Get File Size In Python In Bytes, Kb, Mb, And Gb in Python.
Example 1: Using os.path.getsize()
The os.path.getsize()
function from the os
module is a straightforward way to obtain the size of a file in bytes.
This method directly returns the size of the file in bytes.
In this example, the code uses Python OS Module to get the size of a file named ‘example.txt’. It then converts the file size from bytes to kilobytes, megabytes, and gigabytes and prints the results with two decimal places.
Python3
import os file_path = 'example.txt' file_size_bytes = os.path.getsize(file_path) # Conversion to kilobytes, megabytes, and gigabytes file_size_kb = file_size_bytes / 1024 file_size_mb = file_size_kb / 1024 file_size_gb = file_size_mb / 1024 print (f "File Size (Bytes): {file_size_bytes} B" ) print (f "File Size (KB): {file_size_kb:.2f} KB" ) print (f "File Size (MB): {file_size_mb:.2f} MB" ) print (f "File Size (GB): {file_size_gb:.2f} GB" ) |
Output :
File Size (Bytes): 2359 B
File Size (KB): 2.30 KB
File Size (MB): 0.00 MB
File Size (GB): 0.00 GB
Example 2: Using os.stat()
Method
The os.stat()
function can provide more detailed information about a file, including its size. This method allows for greater flexibility in extracting various file attributes.
In this example, code utilizes Python’s `os` module to gather information about the file ‘example.txt’, including its size in bytes. It then performs conversions to represent the file size in kilobytes, megabytes, and gigabytes. The final output displays the file size in each unit with two decimal places.
Python3
import os file_path = 'example.txt' file_info = os.stat(file_path) file_size_bytes = file_info.st_size # Conversion to kilobytes, megabytes, and gigabytes file_size_kb = file_size_bytes / 1024 file_size_mb = file_size_kb / 1024 file_size_gb = file_size_mb / 1024 print (f "File Size (Bytes): {file_size_bytes} B" ) print (f "File Size (KB): {file_size_kb:.2f} KB" ) print (f "File Size (MB): {file_size_mb:.2f} MB" ) print (f "File Size (GB): {file_size_gb:.2f} GB" ) |
Output :
File Size (Bytes): 2359 B
File Size (KB): 2.30 KB
File Size (MB): 0.00 MB
File Size (GB): 0.00 GB
Contact Us