How to get the file size of a file using Python !

Published on Aug. 22, 2023, 12:12 p.m.

You can use the syntax below in order to get the file size .

Steps to Get the File Size Using Python .

Step 1 : capture the path where the file is stored.

Step 2: Get file size using Python .

import os.path

file_path = r'path where the file is stored\file name.file extension'
file_size = os.path.getsize(file_path)

print(file_size)

The complete code to get the file size in bytes is:

import os.path

file_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
file_size = os.path.getsize(file_path)

print(file_size)

As you can see, the file size is indeed .

2239488

Step 3 (Optional): Get the file size in bytes, kilobytes, megabytes and gigabytes

import os.path

file_path = r'path where the file is stored\file name.file extension'
file_size = os.path.getsize(file_path)

print('File size in Bytes: ' + str(file_size))
print('File size in Kilobytes: ' + str(file_size/1024))
print('File size in Megabytes: ' + str(file_size/1024**2))
print('File size in Gigabytes: ' + str(file_size/1024**3))

Here is the complete code in the context of .

import os.path

file_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
file_size = os.path.getsize(file_path)

print('File size in Bytes: ' + str(file_size))
print('File size in Kilobytes: ' + str(file_size/1024))
print('File size in Megabytes: ' + str(file_size/1024**2))
print('File size in Gigabytes: ' + str(file_size/1024**3))

Get the File Size using Pathlib

from pathlib import Path

file_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
file_size = Path(file_path).stat().st_size

print(file_size)

You’ll then see the result :

2239488

Alternatively, the code below can be used to get the size in bytes, kilobyte, gigabytes:

from pathlib import Path

file_path = r'C:\Users\Ron\Desktop\Test\Products.txt'
file_size = Path(file_path).stat().st_size

print('File size in Bytes: ' + str(file_size))
print('File size in Kilobytes: ' + str(file_size/1024))
print('File size in Megabytes: ' + str(file_size/1024**2))
print('File size in Gigabytes: ' + str(file_size/1024**3))

Here is the result that happened.

File size in Bytes: 2239488
File size in Kilobytes: 2187.0
File size in Megabytes: 2.1357421875
File size in Gigabytes: 0.0020856857299804688