0

I come from a R background and now want to learn Python. I run Python using RStudio and want to show the directory of where the current python script is located. For this I followed this tutorial. I have this script:

import os
result = os.path.join(os.path.dirname(__file__))
print(result)

When I execute it I get this result:

>>> import os
>>> result = os.path.join(os.path.dirname(__file__))
NameError: name '__file__' is not defined
bash-asker
  • 41
  • 5
  • Does [this](https://stackoverflow.com/a/3430395/5165980) answer your question ? – Aymen Dec 20 '22 at 16:26
  • 1
    What do you expect `__file__` to contain when you're using the interactive REPL instead of running the script from a file? – Barmar Dec 20 '22 at 16:29
  • So you @Barmar mean there is no way to show it in the RStudio console? In R this is possible... If there is a way I'd happy to know. – bash-asker Dec 20 '22 at 16:37
  • What do you expect it to show? There's no current file when you're entering code in the terminal. If you want to know your current directory, use `os.getcwd()` – Barmar Dec 20 '22 at 16:42
  • The code in my initial question is written inside a .py script file. So I thought somehow you could manage to get information about where the py-file, in which the code is written, is located. In R language the exact same thing is possible, so I thought it was also possible in Python. This is how it works in R: https://stackoverflow.com/questions/13672720/r-command-for-setting-working-directory-to-source-file-location-in-rstudio – bash-asker Dec 20 '22 at 19:05

0 Answers0