Python
Programming
File Handling
Code Tutorial
Python File Size

How do I check file size in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Python, there are several ways to check the size of a file, each suitable for different use cases and preferences in file handling. Checking the size of a file is a common task in many applications, such as file management tools, data analysis where input data comes from files, or any automation scripts where files need to meet certain size criteria before processing. Below, we'll explore several methods using Python's built-in libraries like os and pathlib, and discuss when each might be most appropriate.

Using the os Module

One of the most straightforward ways to retrieve the size of a file in Python is by using the os module, which provides a function called stat() that performs a stat system call on the specified path.

Example:

python
1import os
2
3# Specify the path to the file
4file_path = 'example.txt'
5
6# Get the size of the file
7file_size = os.path.getsize(file_path)
8
9print(f"The size of the file is: {file_size} bytes")

This method directly retrieves the size of the file in bytes. It’s a fast and effective way to get file size, working well in both scripts and larger applications.

Using the pathlib Module

Introduced in Python 3.4, pathlib offers an object-oriented approach to handling filesystem paths. It encapsulates the file system path in an object allowing to perform various operations related to file systems, including checking file sizes.

Example:

python
1from pathlib import Path
2
3# Create a Path object
4file_path = Path('example.txt')
5
6# Get the size of the file
7file_size = file_path.stat().st_size
8
9print(f"The size of the file is: {file_size} bytes")

This method also provides the size in bytes, and pathlib tends to be more intuitive by using methods directly associated with the file object.

Using os.stat Directly

Similar to os.path.getsize, you can use os.stat to get a variety of metadata about the file, of which size is just one attribute.

Example:

python
1import os
2
3file_path = 'example.txt'
4file_stat = os.stat(file_path)
5
6print(f"The size of the file is: {file_stat.st_size} bytes")

This approach is particularly useful if you also need other metadata about the file without requiring multiple system calls.

Table: Comparison of Methods

MethodModuleCode ExampleUsage Note
getsizeos.pathos.path.getsize(file_path)Straightforward, gets size only
statpathlibPath('file').stat().st_sizeOOP approach, intuitive
statosos.stat(file_path).st_sizeRich file metadata

Additional Tips and Considerations

  • Performance Considerations: When dealing with a large number of files, it’s important to consider the performance implications of the method chosen. Generally, methods involving fewer syscalls and operations will be faster.
  • Handling Exceptions: None of these methods will work if the file does not exist or if there are permission issues. Always handle exceptions such as FileNotFoundError and PermissionError appropriately.
  • File Size Formatting: While sizes are returned in bytes, you may want to format these into kilobytes, megabytes, etc., for readability. This can be done through simple mathematical transformations.

Example of Formatting File Size:

python
file_size_kb = file_size / 1024  # Convert to kilobytes
print(f"The size of the file is: {file_size_kb:.2f} KB")

Conclusion

Choosing the right method to check the file size in Python can depend on your specific needs such as performance concerns, programming style preference (procedural vs OOP), or readability. The os and pathlib modules cover most needs effectively, and understanding their differences can help in deciding the best tool for the job.


Course illustration
Course illustration

All Rights Reserved.