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
  • 530,221
  • 131
  • 937
  • 1,214
CutePoison
  • 4,679
  • 5
  • 28
  • 63

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
  • 985
  • 3
  • 11
  • 28
2

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

import os.path

print(os.path.dirname(__file__))
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
0

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

import os

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