How to Get File Size in Python?

12-Mar-2022

.

Admin

How to Get File Size in Python?

Hi Guys,

In this blog, I will show you how to get file size in python. we will talk about python get file size. I am going to learn you how to get the file size in Python.

There are different methods to get the size of a file in python and this article explains 4 of those methods with examples.

Python’s os module provides a stat function which takes a path as argument. This path may be a string or a path object and returns a structure containing statistical details about the path supplied.

Let's see the bellow examples:

Example 1


example1.py

# import os module

import os

filePath = 'd:/IMG-20210203-WA0004.jpg'

fileSize = os.path.getsize(filePath)

print("File Size = ", fileSize, "bytes")

Run Example

python example1.py

Output:

('File Size = ', 724953, 'bytes')

Example 2

example2.py

# import os module

import os

filePath = 'd:/IMG-20210203-WA0004.jpg'

file_size = os.stat(filePath)

print("File Size = ", file_size.st_size, "bytes")

Run Example

python example2.py

Output:

('File Size = ', 724953, 'bytes')

Example 3

example3.py

# open file

filePath = 'd:/IMG-20210203-WA0004.jpg'

file = open(filePath)

# get the cursor positioned at end

file.seek(0, os.SEEK_END)

# get the size

print("File Size = ", file.tell(), "bytes")

Run Example

python example3.py

Example 4

example4.py

# using pathlib module

from pathlib import Path

# open file

Path(r'd:/IMG-20210203-WA0004.jpg').stat()

# getting file size

file=Path(r'd:/IMG-20210203-WA0004.jpg').stat().st_size

# display the size of the file

print("File Size = ", file, "bytes")

Run Example

python example4.py

Output:

('File Size = ', 724953, 'bytes')

It will help you....

#Python