Home » How to Check the File Size in python

How to Check the File Size in python

Spring Framework Basics Video Course
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Oracle Java Certification

In this example, you will learn to check the file size in python.

We will show 2 different ways to do this

Table of Contents

Example 1

Using stat() from the os module, you can get the details of a file.

We then use the st_size attribute of stat() method to get the file size. The file size is returned in bytes.

import os

file_stat = os.stat('readme.txt')
print(file_stat.st_size)

When you run this you will see something like this

>>> %Run filesize1.py
2797

Example 2

from pathlib import Path

file = Path('readme.txt')
print(file.stat().st_size)

When you run this you will see something like this

>>> %Run filesize2.py
2797

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More