Python Check File Size
In this tutorial, you’ll learn how to get file size in Python.
Whenever we work with files, sometimes we need to check file size before performing any operation. For example, if you are trying to copy content from one file into another file. In this case, we can check if the file size is greater than 0 before performing the file copying operation.
In this article, We will use the following three methods of an OS and pathlib module to get file size.
os.path module:
- os.path.getsize(‘file_path’) : Return the file size in bytes.
- os.stat(file).st_size : Return the file size in bytes
Pathlib module:
- pathlib.Path(‘path’).stat().st_size : Return the file size in bytes.
os.path.getsize() Method to Check File Size
For example, you want to read a file to analyze the sales data to prepare a monthly report, but before performing this operation we want to check whether the file contains any data.
The os.path module has some valuable functions on pathnames. Here we will see how to use the os.path module to check the file size.
-
Important the os.path module
This module helps us to work with file paths and directories in Python. Using this module, we can access and manipulate paths
A file path defines the location of a file or folder in the computer system. There are two ways to specify a file path.
Absolute path: which always begins with the root folder. The absolute path includes the complete directory list required to locate the file. For example, /user/Pynative/data/sales.txt is an absolute path to discover the sales.txt. All of the information needed to find the file is contained in the path string.
Relative path: which is relative to the program’s current working directory.
To maintain uniformity across the operating system, use the forward-slash ( / ) to separate the path. It’ll work across Windows, macOS, and Unix-based systems, including Linux.
Use the os.path.getsize(‘file_path’) function to check the file size. Pass the file name or file path to this function as an argument. This function returns file size in bytes. It raises OSError if the file does not exist or is inaccessible.
Example To Get File Size
Output:
Get File Size in KB, MB, or GB
- First, get the file size using the getsize() function.
- Next, convert bytes to KB or MB.
Use the following example to convert the file size in KB, MB, or GB.
Output:
os.stat() Method to Check File Size
The os.stat() method returns the statistics of a file such as metadata of a file, creation or modification date, file size, etc.
- First, import the os module
- Next, use the os.stat(‘file_path’) method to get the file statistics.
- At the end, use the st_size attribute to get the file size.
Note: The os.path.getsize() function internally uses the os.stat(‘path’).st_size .
Example:
Output:
Pathlib Module to Get File Size
From Python 3.4 onwards, we can use the pathlib module, which provides a wrapper for most OS functions.
- Import pathlib module: Pathlib module offers classes and methods to handle filesystem paths and get data related to files for different operating systems.
- Next, Use the pathlib.Path(‘path’).stat().st_size attribute to get the file size in bytes
Example:
Output:
Get File Size of a File Object
Whenever we use file methods such as read() or a write(), we get a file object in return that represents a file.
Also, sometimes we receive a file object as an argument to a function, and we wanted to find a size of a file this file object is representing.
All the above solutions work for a file present on a disk, but if you want to find file size for file-like objects, use the below solution.
We will use the seek() function to move the file pointer to calculate the file size. Let’s see the steps.
- Use the open() function to open a file in reading mode. When we open a file, the cursor always points to the start of the file.
- Use the file seek() method to move the file pointer at the end of the file.
- Next, use the file tell() method to get the file size in bytes. The tell() method returns the current cursor location, equivalent to the number of bytes the cursor has moved, which is nothing but a file size in bytes.
Example:
Output:
Sumary
In this article, We used the following three methods of an OS and pathlib module to get file size.
os.path module:
- os.path.getsize(‘file_path’) : Return the file size in bytes.
- os.stat(file).st_size : Return the file size in bytes
Pathlib module:
- pathlib.Path(‘path’).stat().st_size : Return the file size in bytes.
Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
About Vishal
Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!
Related Tutorial Topics:
Python Exercises and Quizzes
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
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.
We can get file size in Python using the os module.
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.
Output:
File Size In Python
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.
Python File Size Relative Path NotImplementedError
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
How to Check File and Folder Size in Python?

Python is one of the most versatile programming languages. With it, you’ll be able to build from a small CLI (Command-line interface) program to a complex web application.
However, one of its most underrated features is the capability to interact with operative systems. Managing OS operations with Python can save you tons of time when creating automation processes.
Let’s see how Python interacts with the OS.
How Python interacts with the OS?

No one can live isolated from their environments. That also applies in Python, where sometimes is fundamental to interact with the operative system to get stuff done.
Python has several modules that let us interact with the OS. The most used are os, sys, pathlib, and subprocess.
Since they are built-in modules, you won’t need to install them with PIP. You can import all of them with the following statement:
The below list indicates the main functionality of each one of these imports:
- Os: Portable way of using system-specific (Depending on your OS) functionality. It is the right choice in most cases unless you need something more advanced
- Sys: System-specific parameters and functions. This module provides access to interpreter variables and functions. The os module interacts with the operative system and sys interacts with the Python interpreter
- Pathlib: Advanced path usage. Lets you represent filesystems as objects, with the pertinent semantic for each OS.
- Subprocess: Execution and subprocesses management directly from Python. That involves working with the stdin , stdout , and return codes. You can learn more about it by reading our Python subprocess guide.
There are high-level libraries that include even more specific functionality depending on your needs. However, most of the time you’re good to go with the above modules.
Note: Most of the functions provided by these modules will have a different output depending on your OS. Remember that usually, the best match is UNIX and Python.
Now you have a quick grasp on how Python interacts with the OS, let’s jump into the methods of checking file and folder size. All of the following solutions are available in the File and folder size in the Python GitHub repository
Using os.stat().st_size
In this method, we’re going to use the stat() function from the os module. It returns a lot of information about a specific path.
Note: The os.path.getsize() function also gets the job done. The advantage of using os.stat().st_size is that it doesn’t follow simlinks.
Before continuing, let’s create a testing file named lorem.txt, in which we’re going to paste some dumb text. We can visit a Lorem Ipsum text generator and paste the text into the lorem.txt file.
In the same directory, create a file with the name method1.py and paste the code below:
Let’s break down what we’re doing with this code:
- In the first line, we’re importing the os module
- The size variable contains the size of the file lorem.txt
- The os.stat() function returns a bunch of info related to the file
- The st_size attribute represents the size of the file
Try to run the Python script. You’ll get a different result depending on the content of your lorem.txt file.
Output:
The output is represented in bytes. This is not readable at all, so let’s humanize it so we can have a better perspective of the size of the file.
First, install the humanize package, by running the following command in your shell:
Then you can use the naturalsize() function that converts a value in bytes to readable file size, for instance, KB, MB, GB, or TB.
At first, the code above prints the size of the file in bytes then prints the result in a readable size.
Output:
Using Pathlib
Although pathlib is designed to work exclusively with paths, it incorporates some useful functions from other modules as methods of Path objects (Instances of the Path class).
Create a file method2.py and import the Path class.
Then create a Path object passing the path to the lorem.txt file as an argument.
Now, you can access the stat() method of the Path class. It works the same as the os.stat() function, therefore you’ll be able to print the size of the file.
Output:
As you can see, we got the same result as with the first method we used. The result above is also printed in byte format, so we can use the humanize module to make it readable.
This code produces the following output:
Using Unix commands with Subprocess:
The subprocess module, allows us to call and manage subprocess from Python. Therefore we can run any command and treat its output directly in Python.
Note: This method only works if you’re running a Unix OS (Linux, Mac)
Open a file method3.py and paste the code below:
Diving into this piece of code:
- We import the run function from the subprocess module
- The variable process contains the result of running the command du lorem.txt
- du is a Linux utility that allows us to get the disk space of a file
- capture_output gives us access to the standout (standard output) attribute
- text means we’re storing the output as a string instead of bytes
If you run the code above you’ll get the following output:
As you can see it’s giving us the size and the name of the file. If you only want to get the size of the file, you’ll need to split the output (remember it’s a string) and print the first element.
Output:
This output isn’t readable at all. We can infer that the measurement unit used is KB (because of the previous methods), but no one else could guess the size of the file.
To solve this problem, we can make use of the -h (human-readable) flag.
Note: You can get a manual of this command by running man du, or du –help.
Now the output of this script will be much more readable:
If you want to know more about the subprocess module and possible applications, check out our Python subprocess guide.
Get the Size of a Folder Recursively
If you want to get the size of a folder, you’ll need to iterate over each file present in the directory and its sub-directories. We’ll do it with two methods:
- Iterating over a Path with pathlib
- Using the du command with subprocess
The following code will be using a path to a test directory inside my home folder. You’ll need to replace the path of that file for the directory you want to get the size.
Iterating over a Path with pathlib
Let’s see how you can get the size of a directory by iterating over the sizes of the files.
This piece of code seems a little bit scary, let’s break down what each part is doing.
- Import the Path class and the naturalsize() function
- Define the get_size() function with a parameter path, which points to the current directory by default.
- The size variable is just a placeholder in which we’ll be adding the size of each file
- Iterate over each file of the path
- The rglob() method recursively returns the files that match the pattern
Of course, I’m testing out the function with a directory available only in my machine. Don’t forget to change the path to a folder that exists on your computer.
In my case, I get the following output:
Using the du Command with Subprocess
This approach has some advantages:
- The result is a little bit more accurate
- It’s much faster
We’re using the same approach as method 3, but this time we’re getting the size of a directory instead of a file.
Output:
As you can see these two ways of getting the size of a folder, returns a slightly different result. The bigger the directory is the more difference you’ll get.
It’s up to you to choose between the pathlib or the subprocess approaches. If you know you’ll be using Linux every time use subprocess, else you can use the pathlib solution.
To sum Up
Python results extremely handy when interacting with the OS. You can automate processes and save a lot of time with Python. The main modules to interact with the os are os, sys, path, and subprocess.
How do I check file size in Python?

You need the st_size property of the object returned by os.stat . You can get it by either using pathlib (Python 3.4+):
Output is in bytes.
The other answers work for real files, but if you need something that works for «file-like objects», try this:
It works for real files and StringIO’s, in my limited testing. (Python 2.7.3.) The «file-like object» API isn’t really a rigorous interface, of course, but the API documentation suggests that file-like objects should support seek() and tell() .
Edit
Another difference between this and os.stat() is that you can stat() a file even if you don’t have permission to read it. Obviously the seek/tell approach won’t work unless you have read permission.
Edit 2
At Jonathon’s suggestion, here’s a paranoid version. (The version above leaves the file pointer at the end of the file, so if you were to try to read from the file, you’d get zero bytes back!)