5

Set-up

I run a script on my computer, located in the directory Users/path/to/my/script.py.

In the script, I use the path to the script, e.g.,

sub_path = 'Users/path/to/my/'
os.chdir(sub_path + 'other_script/') 

As you can see, I define sub_path in the code 'manually'.


Problem

I don't want to define the sub_path manually, I'd rather have Python do it for me.

I'm looking for something similar to the code I use to obtain the current working directory: os.getcwd(), but then a code to obtain the directory of the current file.

I mainly find answers similar to this one, which says,

os.path.abspath(os.path.dirname(__file__))

but in the Spyder & Anaconda set-up, this generates a NameError: name '__file__' is not defined.

What can I do?

LucSpan
  • 1,831
  • 6
  • 31
  • 66
  • that's probably because you are running part of your code inside the ipython commandline. So the commandline doesn't have a `__file__` property. Use the play button to run the whole script and it should be fine. – anishtain4 May 07 '18 at 14:35

4 Answers4

1

You if you want to move back one folder/directory you use the .. in your file path.

os.chdir('../other_scripts/')

will work. You may fine it helpful to view this or the wiki. If you want to move from where you currently are you can use './new_dir/'. If you want to automate how to find other files you may want to read here which says to use os.walk. This may be the same question.

lwileczek
  • 2,084
  • 18
  • 27
1

Mark8888 pointed out to run the whole script (run file (F5)) instead of just pieces of the script

this way multiple approaches should work to get the script file location and change the current working directory

import os
# directory of script file
print(os.path.abspath(os.path.dirname(__file__)))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(__file__)))
# current working directory
print(os.getcwd())

also

import os
import sys
# directory of script file
print(os.path.abspath(os.path.dirname(sys.argv[0])))
# change current working directory
os.chdir(os.path.abspath(os.path.dirname(sys.argv[0])))
# current working directory
print(os.getcwd())
Thomas W.
  • 31
  • 1
  • 1
  • 3
0

I add the following lines to any script I run in case I need to access data relative to the location of the script

import sys
script = sys.argv[0]
print(script)
'C:/SomeFolder/A_Subfolder/CurrentlyRunningScript.py'  # changed obviously
NaN
  • 2,212
  • 2
  • 18
  • 23
  • Thank you for thinking with me. Your solution doesn't work for me, it gives me a `script = ''`. – LucSpan May 08 '18 at 10:33
  • It only works if you are running a script from within a python IDE, I suspect then you are launching python.exe 'c:/somescript.py' – NaN May 08 '18 at 16:29
-2

First, save your Jupyter Notebook. Second, locate the directory your Jupyter Notebook is stored in. Thirdly, ensure that your Jupyter Notebook and CSV file are in the same place.