- Python How to Check File Size (Theory & Examples)
- 4 Ways to Find the File Size in Python
- 1. The ‘os.path’ Module
- How to Check File Size with ‘os.path’?
- Example
- 2. The ‘os.stat’ Function
- Example
- 3. The ‘file’ Object
- How to Check File Size with ‘file’ Object?
- Example
- 4. The ‘pathlib’ Module
- How to Check File Size with ‘pathlib’?
- Example
- Read Also
- How to Get File Size in Python
- File Size in Python
Python How to Check File Size (Theory & Examples)
To check the size of a file in Python, use the os.path.getsize() method. This method takes the path of the file as an argument and returns the size of the file in bytes.
import os file_path = '/path/to/file.txt' file_size = os.path.getsize(file_path) print(f'The size of the file is bytes.')
The os module is part of the standard library. Thus, you do not need to install it. It is available out of the box in all Python installations.
This is a complete guide to checking the file size in Python.
If you’re looking for a quick answer, the above will surely do! But if you’re looking to find alternative ways to better match your project-specific needs or if you’re just exploring, keep on reading.
This guide teaches you four different ways to get the file size in Python. Besides, you will learn how the different approaches work.
Let’s jump into it!
4 Ways to Find the File Size in Python
The four most common approaches to finding the size of a files using Python are:
- Use the os.path.getsize() method from the os module, which is part of the standard library. This method takes the path of the file as an argument and returns the size of the file in bytes.
- Use the os.stat() method from the os module, which returns a stat_result object that contains information about the file, including its size in bytes. You can access the file size using the st_size attribute of the stat_result object.
- Use the file.tell() method on an open file object, which returns the current position of the file pointer within the file. You can use the file.seek() method to move the file pointer to the end of the file and then call file.tell() to get the size of the file.
- Use the pathlib.Path.stat() method from the pathlib module, which is part of the standard library. This method takes the path of the file as an argument and returns a stat_result object that contains information about the file, including its size in bytes. You can access the file size using the st_size attribute of the stat_result object.
Let’s take a closer look at each of these approaches with examples.
1. The ‘os.path’ Module
The os.path module is a module in the Python standard library that provides functions for working with files and directories. The os.path module is typically used to check the properties of a file or directory, such as its size, permissions, and whether it exists.
Some of the common methods in the os.path module include:
- os.path.exists() : checks if a path exists
- os.path.isdir() : checks if a path is a directory
- os.path.isfile() : checks if a path is a regular file
- os.path.join() : joins two or more path components
- os.path.getsize() : returns the size of a file in bytes
In this guide, the os module is useful because it allows for checking the size of a file.
How to Check File Size with ‘os.path’?
Here is a code skeleton that shows how you can use the os.path module to check the file size:
import os file_path = '/path/to/file.txt' file_size = os.path.getsize(file_path) print(f'The size of the file is bytes.')
Just replace the ‘ path/to/file ‘ with whatever the path is with respect to the Python file you’re running the script from.
For example, if the file is in the same folder as the Python file, the path to the file is the name of the file. Otherwise, you need to use the directory names and backslashes to construct the path to the target file.
Example
As a concrete example, here I’ve got two files:
The sizefinder.py file is a Python file in which I check the size of the sample.txt file.
Because the files exist in the same folder, the path of the file is just the name of the file.
Here’s what the code looks like:
import os file_path = 'sample.txt' file_size = os.path.getsize(file_path) print(f'The size of the file is bytes.')
By running the above code you get a result like this:
The size of the file is 150 bytes.
2. The ‘os.stat’ Function
To check the size of a file in Python, you can also use the os.stat() method from the os module introduced earlier.
This method takes the path of the file as an argument and returns a stat_result object that contains information about the file, including its size in bytes.
Here’s what a generic solution might look like:
import os file_path = '/path/to/file.txt' file_info = os.stat(file_path) file_size = file_info.st_size print(f'The size of the file is bytes.')
Where you need to replace the ‘ path/to/file.txt ‘ with the actual path to the target file.
Example
Let’s continue with the simple setup in the earlier example. Here are my two files:
The sizefinder.py file is a Python file in which I check the size of the sample.txt file.
Here’s the code you need to place in the sizefinder.py file to find the size of sample.txt :
import os file_path = 'sample.txt' file_info = os.stat(file_path) file_size = file_info.st_size print(f'The size of the file is bytes.')
The size of the file is 150 bytes.
3. The ‘file’ Object
In Python, a file object provides methods for reading and writing files. The file object is typically used to open a file, read or write data to the file, and close the file once you’re done.
This is what reading a file with the file object might look like:
file = open('/path/to/file.txt') contents = file.read() print(contents) file.close()
In this example, we use the open() function to create a file object for the file at the given path. We then use the file.read() method to read the contents of the file into a string, which we print using the print() function. Finally, we close the file by calling the file.close() method.
The file object provides a number of other methods for reading and writing to files, such as file.write() for writing data to the file and file.seek() for moving the file pointer to a specific position within the file. The latter is useful in many cases, such as when you’re looking to find the size of the file.
How to Check File Size with ‘file’ Object?
To check the size of a file in Python, you can use the file.tell() method, which returns the current position of the file pointer within the file. To call this method, first seek to the end of the file using file.seek(0, 2) and then call file.tell() to get the size.
file = open('/path/to/file.txt') # Seek to the end of the file file.seek(0, 2) # Get the current position of the file pointer file_size = file.tell() print(f'The size of the file is bytes.') file.close()
Here you open the file using the open() function and then seek to the end of the file by passing 0 as the first argument and 2 as the second argument to file.seek() . This sets the file pointer to the end of the file. We then call file.tell() to get the current position of the file pointer, which is the size of the file in bytes.
Remember to close the opened file too!
Example
Let’s continue with the setup seen in earlier examples.
The sizefinder.py file is a Python file in which I check the size of the sample.txt file.
This is what the code looks like:
file = open('sample.txt') # Seek to the end of the file file.seek(0, 2) # Get the current position of the file pointer file_size = file.tell() print(f'The size of the file is bytes.') file.close()
The size of the file is 150 bytes.
4. The ‘pathlib’ Module
The pathlib module is a module in the Python standard library that provides an object-oriented interface for working with files and directories. This module is commonly treated as the replacement for the os module.
The pathlib module provides the Path class, which represents a file or directory path. This class provides a number of methods for working with paths, such as Path.exists() for checking if a path exists, Path.mkdir() for creating a directory, and Path.open() for opening a file.
How to Check File Size with ‘pathlib’?
To check the size of a file in Python, you can use the pathlib.Path.stat() method from the pathlib module.
This method takes the path of the file as an argument and returns a stat_result object that contains details of the file, including its size.
from pathlib import Path file_path = Path('/path/to/file.txt') file_info = file_path.stat() file_size = file_info.st_size print(f'The size of the file is bytes.')
Notice that the pathlib module is often more convenient to use than the traditional os.path module, which uses strings to represent paths.
Example
Let’s see a concrete example by continuing with the setup seen in earlier examples.
The sizefinder.py file is a Python file in which I check the size of the sample.txt file.
This is what the code looks like:
from pathlib import Path file_path = Path('sample.txt') file_info = file_path.stat() file_size = file_info.st_size print(f'The size of the file is bytes.')
The size of the file is 150 bytes.
Thanks for reading. Happy coding!
Read Also
How to Get File Size in Python
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
File Size in Python
The python os module has stat() function where we can pass the file name as argument. This function returns a tuple structure that contains the file information. We can then get its st_size property to get the file size in bytes. Here is a simple program to print the file size in bytes and megabytes.
# get file size in python import os file_name = "/Users/pankaj/abcdef.txt" file_stats = os.stat(file_name) print(file_stats) print(f'File Size in Bytes is ') print(f'File Size in MegaBytes is ')
Output: If you look at the stat() function, we can pass two more arguments: dir_fd and follow_symlinks. However, they are not implemented for Mac OS. Here is an updated program where I am trying to use the relative path but it’s throwing NotImplementedError.
# get file size in python import os file_name = "abcdef.txt" relative_path = os.open("/Users/pankaj", os.O_RDONLY) file_stats = os.stat(file_name, dir_fd=relative_path)
Traceback (most recent call last): File "/Users/pankaj/. /get_file_size.py", line 7, in file_stats = os.stat(file_name, dir_fd=relative_path) NotImplementedError: dir_fd unavailable on this platform
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us