0

Say I have the following /home/my_user/files/path.py which contains print(os.getcwd()) and I from /home/ run

python3 ./my_user/files/path.py

I get the output /home/. Is there a way to print the folder of which the file being run is e.g /home/my_user/files independantly of where the file is run from?

Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
CutePoison
  • 3,725
  • 4
  • 21
  • 32

3 Answers3

2

This will give you the absolute path of the directory of the executed python file

os.path.dirname(os.path.abspath(__file__))
atin
  • 953
  • 1
  • 9
  • 24
2

You want the directory of the Python file, not the working directory:

import os.path

print(os.path.dirname(__file__))
Konrad Rudolph
  • 506,650
  • 124
  • 909
  • 1,183
0

You need to get the file's realpath, not the current directory

import os

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