Home > front end >  Correct OS path is not being displayed
Correct OS path is not being displayed

Time:04-10

I wanted to get the following path for further processes:

C:\Users\zaidd\Documents\Treasure Hunt\1

However, after the execution of the following statements I get the following path:

Code:

currentLvl = os.getcwd().split("\\")#[-1]
print(currentLvl)
path = os.getcwd()
cwd = os.path.abspath(os.path.join(path, os.pardir))
os.chdir(cwd)
print(path)
print(cwd)

Output:

['C:', 'Users', 'zaidd']
C:\Users\zaidd
C:\Users

Here is the location of my py file just in case it's needed:

C:\Users\zaidd\Documents\Treasure Hunt\1\IT-Treasure-Hunt.py

CodePudding user response:

It seems you just want the path to the directory containing the running python file. This is the easiest way that I know of:

import pathlib
directory = pathlib.Path(__file__).parent.resolve()

In your case, directory would end up as C:\Users\zaidd\Documents\Treasure Hunt\1

  • Related