Write a Python Program to Check the File Size

As a Python programmer, it is important to be able to check the size of a file, especially when working with large amounts of data.

Checking the size of a file can help you manage your data storage and ensure that you are not exceeding any limits.

In Python, you can use the os module to check the size of a file.

Here is a simple program that demonstrates how to check the size of a file using Python:

import os

# Get the file size in bytes
file_size = os.path.getsize('filename.txt')

print(f'The size of the file is {file_size} bytes')

In the code above, we first import the os module, which provides a way to interact with the operating system.

We then use the os.path.getsize() function to get the size of the file, passing in the filename as an argument.

The getsize() function returns the size of the file in bytes, which we store in the file_size variable.

Finally, we print the size of the file using a formatted string, which includes the file_size variable.

You can use this program to check the size of any file by simply changing the filename in the os.path.getsize() function.


In conclusion, checking the size of a file is an important part of managing your data storage.

With the os module in Python, it is easy to check the size of a file and ensure that you are staying within any limits or constraints.