How To Get File Size In Python?

Files are used to store different types and sizes of data. The size of a file can be printed in different ways in Python. In this tutorial, we will examine how to get file size in python?

Get File Size with getsize() Method

The most popular way to get the size of a file in Python is using the getsize() method. The getsize() method is provided via the os.path module. In order to use getsize() method the os module should be imported.

import os

os.path.getsize("/home/ismail/cities.txt")

The output is like below. The file size unit is byte. So the following output means the file named cities.txt is 63 bytes.

63

If you are using Windows operating system which has a different path naming convention the backslashes should be used two times to express a single backslash.

import os

os.path.getsize("C:\\users\ismail\cities.txt")

Convert File Size To KB (KiloByte), MB (MegaByte), GB (GigaByte)

As stated previously the returned file sizes are expressed as byte units. But the files are bigger which can be expressed as KB, MB, or GB in size. So some calculations should be done in order to express file sizes as KB (KiloByte), MB (MegaByte), GB (GigaByte). In the following example, we will calculate KB, MB, GB sizes and set them into variables named size_KB, size_MB, size_GB.

import os

size = os.path.getsize("C:\\users\ismail\cities.txt")

size_KB = size/1024;

size_MB = size/(1024*1024);

size_KB = size/(1024*1024*1024);

Get File Size with os.stat.st_size Attribute

The os module also provides the attributed named st_size in order to get the size of the specified file. The complete path of the st_size attribute is os.stat(PATH).st_size. Here the PATH is the file path which can be an absolute or relative path.

import os

size = os.stat("/home/ismail/cities.txt").st_size

Get File Size with Path.stat.st_size Attribute

The file size can be get also using the Path module and its stat() method with the st_size attribute. The complete attribute can be called via Path(PATH).stat().st_size. The PATH is the path of the file which can be absolute or relative.

import Path

size = Path("/home/ismail/cities.txt").stat().st_size

Leave a Comment