![]() |
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 GbBelow, are the methods to Get File Size In Python In Bytes, Kb, Mb, And Gb in Python. Example 1: Using
|
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
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.
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
Reffered: https://www.geeksforgeeks.org
Python |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 15 |