DEV Community

Srinivas Ramakrishna for ItsMyCode

Posted on • Originally published at itsmycode.com on

How to Get File Size in Python?

ItsMyCode |

There are different ways to get file size in Python. We will be using the os module and the pathlib module to check the file size. OS module in Python comes as built-in, and it provides various utility methods to interact with operating system features.

Python get file size

The popular ways to fetch file size in Python are as follows.

  • os.path.getsize()
  • os.stat()
  • seek() and tell()
  • path.stat().st_mode

Method 1: Get file size using os.path.getsize()

The os.path.getsize() function takes a file path as an argument and returns the file size in bytes. If the function cannot find the file or is inaccessible, Python will raise an OSError.

# Import os module
import os

# set the file path
file = "python.pdf"

# Get the file size using os.path.getsize() function
file_size = os.path.getsize(file)

print('File Size in Bytes is ', file_size)
print('File Size in KiloBytes is ', (file_size / 1024))
print('File Size in MegaBytes is ', (file_size / (1024 * 1024)))

Enter fullscreen mode Exit fullscreen mode

Output

File Size in Bytes is 12271318
File Size in KiloBytes is 11983.708984375
File Size in MegaBytes is 11.702840805053711
Enter fullscreen mode Exit fullscreen mode

Method 2: Get file size using os.stat()

The os.stat() function takes a file path as an argument and returns the statistical details of the file as a tuple. The stat() method will get the status of the specified file path, and the st_size attribute will fetch the file size in bytes.

# Import os module
import os

# set the file path
file = "python.pdf"

#If you want to print the file info 
file_info= os.stat(file)
print(file_info)

# Get the file size using os.stat() function
file_size = os.stat(file).st_size

print('File Size in Bytes is ', file_size)
print('File Size in KiloBytes is ', (file_size / 1024))
print('File Size in MegaBytes is ', (file_size / (1024 * 1024)))

Enter fullscreen mode Exit fullscreen mode

Output

os.stat_result(st_mode=33206, st_ino=12103423998770118, st_dev=3351013, st_nlink=1, st_uid=0, st_gid=0, st_size=12271318, st_atime=1632686420, st_mtime=1632608049, st_ctime=1632686420)
File Size in Bytes is 12271318
File Size in KiloBytes is 11983.708984375
File Size in MegaBytes is 11.702840805053711
Enter fullscreen mode Exit fullscreen mode

Method 3: Get file size using seek() and tell()

The other methods perfectly work in the case of an actual file, and if you have something like file-like objects, you could use seek() and tell() to fetch the file size.

There are three steps involved to get the file size.

Step 1: Open the file using the open() function and store the return object into a variable. When the file is opened, the cursor always points to the beginning of the file.

Step 2: File objects provide a seek() method to set the cursor into the desired location. It accepts two arguments start position and the end position. To set the cursor at the end location of the file, use method _ os.SEEK_END._

Step 3: The file object has a tell() method that can get the current cursor position and provides the number of bytes it has moved from the initial position. Basically, it gives the actual file size in bytes format.


# Import os module
import os

# set the file path
file_name = "python.pdf"

# open file using open() function
file = open(file_name)

# set the cursor position to end of file
file.seek(0, os.SEEK_END)

# get the current position of cursor
# this will be equivalent to size of file
file_size= file.tell()


print('File Size in Bytes is ', file_size)
print('File Size in KiloBytes is ', (file_size / 1024))
print('File Size in MegaBytes is ', (file_size / (1024 * 1024)))
Enter fullscreen mode Exit fullscreen mode

Output

File Size in Bytes is 12271318
File Size in KiloBytes is 11983.708984375
File Size in MegaBytes is 11.702840805053711
Enter fullscreen mode Exit fullscreen mode

Method 4: Get file size using path.stat().st_mode

The stat() method of the Path object returns the properties of a file like st_mode , st_dev , etc. and, the st_size attribute of the stat method returns the file size in bytes.

# Import pathlib module
import pathlib

# set the file path
file = "python.pdf"

# Get the file size using pathlib.Path() function
file_size = pathlib.Path(file).stat().st_size

print('File Size in Bytes is ', file_size)
print('File Size in KiloBytes is ', (file_size / 1024))
print('File Size in MegaBytes is ', (file_size / (1024 * 1024)))

Enter fullscreen mode Exit fullscreen mode

Output

File Size in Bytes is 12271318
File Size in KiloBytes is 11983.708984375
File Size in MegaBytes is 11.702840805053711
Enter fullscreen mode Exit fullscreen mode

Note: The pathlib module is available only from *Python 3.4 and above * versions.

All the above methods provide the file size in bytes format. In most cases, if the file size is significant, you would need it in a human-readable format as kilobytes or megabytes.

Python get file size in kb (KiloBytes)

To convert from bytes to Kilobytes , divide the filesize bytes by 1024, as shown in the above examples.

Python get file size in kb (MegaBytes)

To convert from bytes to Megabytes , divide the filesize bytes by (1024 x 1024) as shown in the above examples.

The post How to Get File Size in Python? appeared first on ItsMyCode.

Top comments (1)

Collapse
 
brandonwallace profile image
brandon_wallace • Edited

I thought you might like this.
Here is a function that can convert bytes to a human readable format.
It goes from kilobytes all the way up to exabytes.

def convert_bytes(bytes, unit):
    '''
    Convert bytes to more human readable format.
    For sizes above 1 KB display amount in kilobytes.
    For sizes above 1 MB display amount in megabytes.
    For sizes above 1 GB display amount in gigabytes.
    For sizes above 1 TB...
    '''

    unit = unit.lower()
    if bytes > 1024:
        unit = 'k'
    if bytes > 1048576:
        unit = 'm'
    if bytes > 1048576000:
        unit = 'g'
    if bytes > 1099511627776:
        unit = 't'
    if bytes > 1125899906842618:
        unit = 'p'
    if bytes > 1152921504606847000:
        unit = 'e'
    factor = {'k': 1, 'm': 2, 'g': 3, 't': 4, 'p': 5, 'e': 6}
    return f'{bytes / (1024 ** factor[unit]):.2f} {unit.upper()}B'
Enter fullscreen mode Exit fullscreen mode