Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

import os

A = os.path.join(os.path.dirname(__file__), '..')

B = os.path.dirname(os.path.realpath(__file__))

C = os.path.abspath(os.path.dirname(__file__))

I want to understand the os.path module so that I can start using it.

1 Answer

0 votes
by (107k points)

When a package is loaded from a file in Python, __file__ is set to its directory. You can then use that with other methods to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')

# A is the parent directory of the directory where the program resides.

B = os.path.dirname(os.path.realpath(__file__))

# B is the canonicalized (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))

# C is the absolute path of the directory where the program resides.

You can see the many values returned from these here:

import os

print(__file__)

print(os.path.join(os.path.dirname(__file__), '..'))

print(os.path.dirname(os.path.realpath(__file__)))

print(os.path.abspath(os.path.dirname(__file__)))

Related questions

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...