2

I know that os.get_cwd() returns current directory. But problem is that it returns directory where you execute python, not the certain file exists in.

For example, below is the directory structure:

my_test_dir
├── __init__.py
├── main.py
└── test1
    ├── __init__.py
    └── util.py

Let say I insert print(os.get_cwd()) in util.py. And main.py import util. If I run main.py in my_test_dir, then it prints my_test_dir, not my_test_dir/test1 because I execute this python program in my_test_dir.

What I want to do is to make it print my_test_dir/test1.

Is there any way to do that?

user3595632
  • 4,692
  • 8
  • 43
  • 95
  • Possible duplicate of [what does the \_\_file\_\_ variable mean/do?](https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do) – JRG Jul 29 '17 at 01:57

2 Answers2

2
print(os.path.dirname(__file__))
Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
  • https://stackoverflow.com/questions/9271464/what-does-the-file-variable-mean-do/9271617 – Sam Jul 29 '17 at 01:36
2

Be careful with Windows os, to avoid any kind of trouble, you can do:

import os
os.path.dirname(os.path.abspath(__file__))
Damian Lattenero
  • 15,181
  • 3
  • 34
  • 70