How To Get File Size In Python

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.

# get file size in pythonimport osfile_name = "/Users/pankaj/abcdef.txt"file_stats = os.stat(file_name)print(file_stats)print(f'File Size in Bytes is {file_stats.st_size}')print(f'File Size in MegaBytes is {file_stats.st_size / (1024 * 1024)}')


How to Get File Size in Python

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.

# get file size in pythonimport osfile_name = "abcdef.txt"relative_path ="/Users/pankaj", os.O_RDONLY)file_stats = os.stat(file_name, dir_fd=relative_path)


Traceback (most recent call last): File "/Users/pankaj/.../", line 7, in file_stats = os.stat(file_name, dir_fd=relative_path)NotImplementedError: dir_fd unavailable on this platformHow to Get File Size in Python

Python File Size Relative Path NotImplementedError

  • 219