top of page
90s theme grid background
  • Writer's pictureGunashree RS

How to Check File Size in Python: 4 Simple Methods

Introduction

Knowing the size of a file is often important when you're working with files in Python. Whether you're managing storage space, tracking file transfers, or just curious about the file you're working with, being able to quickly find the file size can be really helpful.


Luckily, Python provides several simple methods to get the size of a file. In this article, we'll go through 4 different ways you can check the file size, and even show you how to convert the size to different units like kilobytes (KB), megabytes (MB), and gigabytes (GB).


By the end, you'll have all the tools you need to easily find the size of any file in your Python programs. Let's dive in!


Check File Size in Python

1. Using `os.path.getsize()`

One of the easiest ways to get the file size in Python is by using the `os.path.getsize()` function. This function takes the file path as an argument and directly returns the size of the file in bytes.


Here's how you can use it:


python

import os
file_path = 'your_file_path'
file_size = os.path.getsize(file_path)
print(f"File Size in Bytes is {file_size}")

This will print out the file size in bytes. Simple, right? The `os.path.getsize()` function is a great choice when you just need a quick and easy way to get the file size.


2. Using `os.stat()`

Another method to get the file size is by using the `os.stat()` function. This function returns a set of file attributes, including the size of the file.


Here's how you can use it:


python

import os
file_path = 'your_file_path'
file_stats = os.stat(file_path)
file_size = file_stats.st_size
print(f"File Size in Bytes is {file_size}")

The `st_size` attribute of the `os.stat()` result gives you the file size in bytes. This method is a bit more involved than the `os.path.getsize()` approach, but it can be useful if you need to access other file attributes as well.


3. Using File Object

If you already have the file open in your Python program, you can use the `seek()` and `tell()` methods to get the file size.


Here's how it works:


python

import os
file = open('your_file_path', 'rb')
file.seek(0, os.SEEK_END)
file_size = file.tell()
print(f"File Size in Bytes is {file_size}")

First, we open the file in binary mode (`'rb'`). Then, we use `file.seek(0, os.SEEK_END)` to move the file pointer to the end of the file. Finally, we call `file.tell()` to get the current position of the file pointer, which is the total size of the file in bytes.


This method can be handy if you're already working with a file object in your code, as it avoids the need to pass the file path to another function.


4. Using `pathlib` Module

For Python 3.4 and later, you can also use the `pathlib` module to get the file size. The `pathlib` module provides a more object-oriented way of working with file paths and attributes.


Here's how you can use it:


python

from pathlib import Path
file_path = Path('your_file_path')
file_size = file_path.stat().st_size
print(f"File Size in Bytes is {file_size}")

The `Path` object represents the file path, and the `stat()` method returns file metadata, including the `st_size` attribute, which gives the file size in bytes.


This method is similar to using `os.stat()`, but the `pathlib` approach can feel a bit more intuitive and readable, especially if you're working with file paths in your code.


Converting File Size to Other Units

While getting the file size in bytes is useful, it's often more practical to display the file size in a more human-readable format, such as kilobytes (KB), megabytes (MB), or gigabytes (GB).


Here's a simple function that can convert the file size from bytes to other units:


python

def convert_bytes(size):
    for x in ['bytes', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024.0:
            return "%3.1f %s" % (size, x)
        size /= 1024.0
file_size = os.path.getsize('your_file_path')
print('File size is', convert_bytes(file_size))

This function takes the file size in bytes as an argument and returns the size in the most appropriate unit, with the value rounded to one decimal place.


For example, if the file size is 2,456,789 bytes, the function will return `"2.3 MB"`. If the file size is 1,234 bytes, it will return `"1.2 KB"`.


By using this function, you can easily display the file size in a more user-friendly way, making it easier for people to understand the size of the file you're working with.




FAQ


1. Why can't I just use `len()` to get the file size?

   The `len()` function in Python is used to get the length of various data structures, like strings, lists, and dictionaries. It doesn't work for getting the size of a file, as files are not considered a data structure in the same way. Instead, you need to use one of the file size-specific methods we covered in this article.


2. Can I get the file size in a human-readable format without using the `convert_bytes()` function?

   Yes, you can use the `format_bytes()` function from the `humanize` library to get the file size in a human-readable format. Here's an example:

python

   import humanize
   file_size = os.path.getsize('your_file_path')
   human_readable_size = humanize.naturalsize(file_size)
   print(f"File size is {human_readable_size}")

   This will output the file size in a more readable format, like "2.3 MB" or "1.2 KB".


3. Why do some of the methods use `os.SEEK_END` when getting the file size?

   The `os.SEEK_END` constant is used to specify that the file pointer should be moved to the end of the file. This is necessary when using the `file.seek()` and `file.tell()` methods to get the file size, as the file pointer needs to be at the end of the file to accurately determine the total size.


4. Can I use these methods to get the size of a directory instead of a file?

   No, the methods we've covered in this article are specifically for getting the size of individual files. To get the size of a directory, you would need to use a different approach, such as recursively traversing the directory and adding up the sizes of all the files within it.


5. Do these methods work the same way on different operating systems?

   Yes, the methods we've discussed in this article should work the same way on all major operating systems, including Windows, macOS, and Linux. The underlying `os` and `pathlib` modules are designed to work cross-platform, so you can use these methods confidently on any system.



Conclusion

In this article, we've covered 4 different ways to get the size of a file in Python:


1. Using `os.path.getsize()`

2. Using `os.stat()`

3. Using File Object

4. Using the `pathlib` module


Each of these methods has its own advantages, so you can choose the one that best fits your needs. Whether you need a quick and simple way to get the file size, or you want to access additional file attributes, there's an option here for you.


We also showed you how to convert the file size from bytes to more human-readable units like KB, MB, and GB, making it easier to understand the size of the files you're working with.


Now that you know these handy techniques, you can start incorporating them into your Python projects and easily manage file sizes like a pro. Happy coding!



External Links:

Comments


bottom of page