Checking the file size is a common operation in Python programming, especially when dealing with file management or data processing applications. By checking the size of a file, you can determine whether it's suitable for upload, processing, or storage, and you can make decisions based on its size.
In this article, you will learn how to utilize Python to check the size of a file. You will explore how to implement this using the built-in os
module and how to handle exceptions to ensure your program is robust.
os.path.getsize()
Import the os
module.
Specify the path to the file whose size you want to check.
Use os.path.getsize()
to retrieve the file size.
import os
file_path = 'example.txt'
file_size = os.path.getsize(file_path)
print("File Size in Bytes:", file_size)
This code retrieves the size of example.txt
in bytes and prints it. os.path.getsize()
directly gives the size of the file located at the specified path.
Use the try
and except
block to handle exceptions.
Attempt to get the file size and catch any FileNotFoundError
.
import os
file_path = 'nonexistent_file.txt'
try:
file_size = os.path.getsize(file_path)
print("File Size in Bytes:", file_size)
except FileNotFoundError:
print(f"File `{file_path}` not found.")
In this example, if the file doesn't exist, it catches the FileNotFoundError
and prints a custom message. Handling exceptions is crucial to prevent your program from crashing when errors occur during file operations.
Import the pathlib
module for object-oriented file system paths.
Create a Path
object and use its stat()
method to get file details.
from pathlib import Path
file_path = Path('example.txt')
file_size = file_path.stat().st_size
print("File Size in Bytes:", file_size)
This block of code demonstrates how to use Pathlib
, a modern file handling method in Python. It provides an object-oriented interface and is often easier to work with than the os
module.
Checking the file size in Python is straightforward using the os
module's os.path.getsize()
method or the more modern Pathlib
approach. Both methods provide efficient ways to retrieve file size, but Pathlib
offers enhanced syntax and additional capabilities. By employing good exception handling practices, as shown in the provided examples, you ensure that your applications are robust and can handle unexpected situations gracefully. Utilize these techniques in your file-handling programs for effective and efficient results.