Skip to content

How to get file size in Python?

  • by
  • 2 min read

Python is one of the easiest programming languages that anyone can pick up and learn at the moment. The language uses simple syntax and is quite powerful and versatile.

Programmers also have the advantage of a massive library of inbuilt functions. In this article, we’re taking a look at how to get a file’s size in Python. 

Also read: How to find the length of a list in Python?

Getting file sizes

There are three ways you can fetch a file’s size in Python.

  • Using the getsize function.
  • Using the stat function.
  • By creating a file object and using it to fetch size. 

We’ll be going over all three of these methods. 

Using the getsize function

The getsize function is a part of the os.path module in Python, which takes a file path as an argument and returns the file size in bytes. 

import OS
size = os.path.getsize('file path here')
print ('File size is:', size, 'bytes')

The snippet above will output the file size in bytes as the os.path.getsize function will fetch the file from the specified location and get its file size. 

Using the stat function

The os module from Python also has a stat function that takes a path as an argument and can return different information depending upon what property you’re using. We’re going to only concern ourselves with the st_size property, which returns the file size in bytes.

import OS
sizeStat = os.stat('path to file')
print ('File size is:', sizeStat, 'bytes')

Using a file object

Lastly, you can open a file using the open function and assign it to an object as a variable. This object will now act as a file handler for various operations, including getting the file size. We’ll be using file.tell() to fetch the file size.

file = open('file path'), os.SEEK_END)
print ('File size is:', file.tell(), 'bytes')

Also read: How to fix Python Memory Error?

Yadullah Abidi

Yadullah Abidi

Yadullah is a Computer Science graduate who writes/edits/shoots/codes all things cybersecurity, gaming, and tech hardware. When he's not, he streams himself racing virtual cars. He's been writing and reporting on tech and cybersecurity with websites like Candid.Technology and MakeUseOf since 2018. You can contact him here: