Python Program to Check the File Size
File size refers to the amount of storage space that a file occupies on a computer’s file system, typically measured in bytes, kilobytes (KB), megabytes (MB), gigabytes (GB), or terabytes (TB).
When a file is created, it occupies a certain amount of space on the file system, depending on its content and format.
Python Code :
You can use the os module in Python to check the size of a file. Here is an example program that demonstrates this:
import os
filename = 'example.txt'
# Get the size of the file in bytes
file_size = os.path.getsize(filename)
# Print the size of the file in a human-readable format
print(f'File size: {file_size} bytes ({file_size/1024:.2f} KB)')
In this program, we first import the os module. We then specify the name of the file we want to check the size of (in this example, example.txt). We use the os.path.getsize() function to get the size of the file in bytes. This function returns an integer representing the number of bytes in the file.
We then print the size of the file in a human-readable format using the print() function. We divide the file size by 1024 to convert it to kilobytes and format the output to two decimal places.
Note that the size of a file can be affected by factors such as the file system block size and the encoding used to store the file. The size reported by os.path.getsize() may not always be accurate in these cases.