0

I want to get the directory that my current .py file is saved in so that I can set the current working directory to this directory programmatically. Like:

import os
file_path = ???
os.chdir( file_path )

I thought you could use __file__ to achieve this, but it says name '__file__' is not defined.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
  • 1
    In Python 2.7, you can use `os.path.abspath(__file__)` to get the absolute path of the current .py file, and then use `os.path.dirname()` to extract the directory containing the file. – Ishaan Adarsh Jul 25 '23 at 09:26
  • Does this answer your question? [Find the current directory and file's directory](https://stackoverflow.com/questions/5137497/find-the-current-directory-and-files-directory) – mkrieger1 Jul 25 '23 at 09:26
  • @IshaanAdarsh This does not seem to be working: `name '__file__` is not defined. I am using Anaconda and Spyder by the way. – AccidentalTaylorExpansion Jul 25 '23 at 09:28
  • Then you have a different problem. `__file__` is only defined if you execute a file as a script. But there is no difference between Python 2 and 3 here. – mkrieger1 Jul 25 '23 at 09:30
  • 1
    @mkrieger1 oh I understand what is going on. I was running the code as a cell and this caused `__file__` to not work – AccidentalTaylorExpansion Jul 25 '23 at 09:33
  • @AccidentalTaylorExpansion Try using `os.path.realpath` not `os.path.abspath`. The error eften occurs with abspath – Ishaan Adarsh Jul 25 '23 at 09:35
  • Just making sure: You know that Python 2 is dead (unsupported) since the beginning of 2020? That was announced 10 years before that date. Do you really have software that couldn't be migrated to Python 3 in over 13 years? – Matthias Jul 25 '23 at 09:51

1 Answers1

0

It turns out I was running the above code as a cell, not as a script. If I do this the following will work

import os

os.chdir(os.path.dirname(__file__))