0

I have a python script in PythonCode folder. I want that I should get the path excluding the PythonCode from it when using os.path.dirname(__file__), currently when I am using os.path.dirname(__file__) it is returning this:-

C:\Users\xyz\Documents\ABC\Python Code

but I need this path:-

C:\Users\xyz\Documents\ABC\

import os

dirname = os.path.dirname(__file__)

print (dirname)

martineau
  • 119,623
  • 25
  • 170
  • 301
Shubham
  • 77
  • 11

4 Answers4

0

You can wrap dirname once again to go up a directory

dirname=os.path.dirname(os.path.dirname(path))
Jason Adhinarta
  • 98
  • 1
  • 4
  • 7
0

Just call os.path.dirname() again on what you have:

import os

dirname = r"C:\Users\xyz\Documents\ABC\Python Code"
wanted = os.path.dirname(dirname)
print(wanted)  # -> C:\Users\xyz\Documents\ABC
martineau
  • 119,623
  • 25
  • 170
  • 301
0

This has been already answered here.

You can do something like this,

import os
print(os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)))
0

The other answers use os.path, but you could also use the standard library pathlib module (https://docs.python.org/3/library/pathlib.html), which some people prefer because of its more intuitive object-oriented interface:

from pathlib import Path

wanted = Path(__file__).parent.parent

wanted_as_string = str(wanted)
Josh Karpel
  • 2,110
  • 2
  • 10
  • 21