Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to get file extension in Python?
Next article icon

How to get file size in Python?

Last Updated : 21 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

We can follow different approaches to get the file size in Python. It’s important to get the file size in Python to monitor file size or in case of ordering files in the directory according to file size. 

Method 1: Using getsize function of os.path module

This function takes a file path as an argument and it returns the file size (bytes). 

Example:

Python3

# approach 1
# using getsize function os.path module
import os
 
file_size = os.path.getsize('d:/file.jpg')
print("File Size is :", file_size, "bytes")
                      
                       

Output:

File Size is : 218 bytes

Method 2: Using stat function of the OS module

This function takes a file path as an argument (string or file object) and returns statistical details about file path given as input. 

Example:

Python3

# approach 2
# using stat function of os module
import os
 
file_size = os.stat('d:/file.jpg')
print("Size of file :", file_size.st_size, "bytes")
                      
                       

Output:

Size of file : 218 bytes

Method 3: Using File Object

To get the file size, follow these steps –

  1. Use the open function to open the file and store the returned object in a variable.  When the file is opened, the cursor points to the beginning of the file.
  2. File object has seek method used to set the cursor to the desired location. It accepts 2 arguments – start location and end location. To set the cursor at the end location of the file use method os.SEEK_END.
  3. File object has tell method that can be used to get the current cursor location which will be equivalent to the number of bytes cursor has moved. So this method actually returns the size of the file in bytes.

Example:

Python3

# approach 3
# using file object
 
# open file
file = open('d:/file.jpg')
 
# get the cursor positioned at end
file.seek(0, os.SEEK_END)
 
# get the current position of cursor
# this will be equivalent to size of file
print("Size of file is :", file.tell(), "bytes")
                      
                       

Output:

Size of file is : 218 bytes

Method 4: Using Pathlib Module

The stat() method of the Path object returns st_mode, st_dev, etc. properties of a file. And, st_size attribute of the stat method gives the file size in bytes.

Example:

Python3

# approach 4
# using pathlib module
from pathlib import Path
 
# open file
Path(r'd:/file.jpg').stat()
 
# getting file size
file=Path(r'd:/file.jpg').stat().st_size
 
# display the size of the file
print("Size of file is :", file, "bytes")
 
# this code was contributed by debrc
                      
                       

Output:

Size of file is : 218 bytes


Next Article
How to get file extension in Python?

D

devanshigupta1304
Improve
Article Tags :
  • Python
  • Python file-handling-programs
  • python-file-handling
Practice Tags :
  • python

Similar Reads

  • How to check file size in Python?
    Prerequisites: os pathlib Given a file, the task here is to generate a Python Script to print its size. This article explains 2 methods to do so. ApproachImport moduleGet file sizeFile in use Name: Data.csv Size: 226 bytes Method1: Using pathlib Path().stat().st_size() function of pathlib module get
    1 min read
  • How to get size of folder using Python?
    In this article, we are going to discuss various approaches to get the size of a folder using python. To get the size of a directory, the user has to walk through the whole folder and add the size of each file present in that folder and will show the total size of the folder.  Steps to be followed:
    3 min read
  • How to get file extension in Python?
    In this article, we will cover How to extract file extensions using Python. How to Get File Extension in Python? Get File Extension in Python we can use either of the two different approaches discussed below: Use the os.path Module to Extract Extension From File in PythonUse the pathlib Module to Ex
    2 min read
  • How to Read from a File in Python
    Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Example File: geeks.txt Hello World Hello Geeksfor
    5 min read
  • How To Read .Data Files In Python?
    Unlocking the secrets of reading .data files in Python involves navigating through diverse structures. In this article, we will unravel the mysteries of reading .data files in Python through four distinct approaches. Understanding the structure of .data files is essential, as their format may vary w
    4 min read
  • How to copy file in Python3?
    Prerequisites: Shutil When we require a backup of data, we usually make a copy of that file. Python supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Here we will learn how to copy a file using Pyt
    2 min read
  • How to find size of an object in Python?
    In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself. Note: Only the memory consumption directly attributed t
    2 min read
  • How to read large text files in Python?
    In this article, we will try to understand how to read a large text file using the fastest way, with less memory usage using Python. To read large text files in Python, we can use the file object as an iterator to iterate over the file and perform the required task. Since the iterator just iterates
    3 min read
  • How to Get directory of Current Script in Python?
    A Parent directory is a directory above another file/directory in a hierarchical file system. Getting the Parent directory is essential in performing certain tasks related to filesystem management.  In this article, we will take a look at methods used for obtaining the Parent directory of the curren
    4 min read
  • How to get the duration of audio in Python?
    It is possible to find the duration of the audio files using Python language which is rich in the use of its libraries. The use of some libraries like mutagen, wave, audioread, etc. is not only limited to extract the length/duration of the audio files but comes with much more functionality. Source A
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences