Get human readable version of file size in Python
In this post, we will explore numerous techniques to acquire file size in human-readable forms like Bytes, Kilobytes (KB), MegaBytes (MB), GigaBytes(GB), and many more.
Get record size in KB, MB, or GB – comprehensible configuration
Many approaches to determining the size of the file in bytes
Method 1: using os.path.getsize()
Syntax:
os.path.getsize(path)
It takes a file path as input and returns the file’s size in bytes for that location. An os.error is raised if the file doesn’t exist or can’t be accessed at the specified location. Therefore, before executing this method, always make sure the file is there.
Python Code will be:
import os def bytes(file_name): #Get file size at given path in bytes sizeoffile = os.path.getsize(file_name) return sizeoffile file_name = 'aman.txt' sizeinbytes = bytes(file_name) print('size of file in bytes : ', sizeinbytes)
The output will be:
size of file in bytes : 28 Process finished with exit code 0
Method 2: using os.stat().st_size
Syntax:
os.stat(path, *, dir_fd=None, follow_symlinks=True)
It takes a string input for the file path and then gives an item of the type stat that contains a number of characteristics about the file at the specified location. st_size, one of the properties, contains the file’s size in bytes.
Python Code will be:
import os def bytes_2(file_name): stat= os.stat(file_name) size1 = stat.st_size return size1 file_name = 'aman.txt' size2 = bytes_2(file_name) print('Size of the file in bytes : ', size2)
The output will be:
Size of the file in bytes : 28 Process finished with exit code 0
These are the ways to print the file size in Bytes. Now with the help of this, we can easily print the file size in different formats like MB, GB, TB, etc.
For this, we create another function in python that takes the file size in Bytes as input, and then with the help of for loop we will divide the file size by 1024 and store the result in another variable, and finally, it will automatically print the file size in another format based on our condition.
Example:
def readable_size(size2, decimal_point=3): for i in ['B', 'KB', 'MB', 'GB', 'TB']: if size2 < 1024.0: break size2 /= 1024.0 return f"{size2:.{decimal_point}f}{i}"
So our final Python code will be:
import os def bytes_2(file_name): stat= os.stat(file_name) size1 = stat.st_size return size1 def readable_size(size2, decimal_point=3): for i in ['B', 'KB', 'MB', 'GB', 'TB']: if size2 < 1024.0: break size2 /= 1024.0 return f"{size2:.{decimal_point}f}{i}" file_name = 'file.xlsx' size2 = bytes_2(file_name) size3=readable_size(size2, decimal_point=3) print('Size of the file in bytes : ', size2) print(size3)
The output will be:
Size of the file in bytes : 17831 17.413KB Process finished with exit code 0
I hope you like this article.
Leave a Reply