How to get the directory from the location where a . py file is running?

Asked

Viewed 7,124 times

0

I have a file. py of setup, so every time it runs I need to know the directory from where it is running, how can I do this?

2 answers

2

To get the absolute path:

import os 
dir_path = os.path.dirname(os.path.realpath(__file__))

To get the relative path:

import os
cwd = os.getcwd()
  • That’s not quite the difference: https://stackoverflow.com/questions/19322836/how-do-i-find-directory-of-the-python-running-script-inside-the-script/19323023#19323023, https://repl.it/repls/IntrepidOrderlyFlicker

  • "cwd" is "Current Working directory" - and has nothing to do with the directory where the file is, but rather the directory from which the program was called to run.

1


Browser other questions tagged

You are not signed in. Login or sign up in order to post.