Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
os
communitycreator
getsize

What is the os.path.getsize() method in Python?

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

Overview

The os.path.getsize() method in Python is used to get the size of a file. If the file doesn’t exist at the specified path, this method raises a FileNotFoundError exception.

Syntax

os.path.getsize(filePath)

Parameters

This method accepts the following parameter:

  • filePath: It is the path of the file. It can be a string or a byte object.

Return value

This method returns an integer value that represents the size of the file in bytes.

Example 1

Let’s look at an example of the os.path.getsize() method in the code snippet below.

main.py
demo.txt
# Import the OS module
from os.path import getsize
# File path
filePath = 'demo.txt'
# Get the file size
fileSize = getsize(filePath)
# Print the file size
print('File size:', fileSize)
Using the os.path.getsize() method in Python

Explanation

  • Line 2: We import the **os** module.
  • Line 5: We declare a variable filePath containing the file path.
  • Line 8: We use the os.path.getsize() method to find the size of the file.
  • Line 11: We print the size of the file on the console.

Output

  • The os.path.getsize() method gets the size of the demo.txt file and prints it on the console.

Example 2

Now, let’s look at an example of the os.path.getsize() method for a non-existing file.

# Import the OS module
from os.path import getsize
# File path
filePath = 'demo.txt'
# Get the file size
fileSize = getsize(filePath)
# Print the file size
print('File size:', fileSize)
Using the os.path.getsize() method in Python

Output

  • If the file is not present at the specified path, this method raises the FileNotFoundError exception.
  • The same is seen in the above code output.

RELATED TAGS

python
os
communitycreator
getsize

CONTRIBUTOR

Shubham Singh Kshatriya

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring