32

When I use the jupyter extension in VScode and run a line of code in jupyter to save a file using relative path,I found the file(iris_tree.dot) in another file. It's just like i debug/run the code in another file path. How can I set the correct path of the jupyter runner?

#%%
from sklearn.tree import export_graphviz
export_graphviz(
tree_clf,
out_file="iris_tree.dot",
feature_names=iris.feature_names[2:],
class_names=iris.target_names,
rounded=True,
filled=True
)
1
  • Check this out stackoverflow.com/a/56091981/6875391, I've changed the setting "python.terminal.executeInFileDir" (Ctrl+Shift+P search "User setting" then search "python.terminal.executeInFileDir") and it looks like pypath was updated Commented Oct 14, 2019 at 1:44

6 Answers 6

77

Just update the value of "Notebook File Root" to ${workspaceFolder} or ${fileDirname}. (Learn more about VSCode directory variables here.)

enter image description here

Sign up to request clarification or add additional context in comments.

7 Comments

For quick copy and paste: ${workspaceFolder} OR ${fileDirname}
I found this more helpful, I didn't see under settings "Python -> data science ..." as @Ian Huff's answer said
This is the correct answer, at least at this moment.
If you're having trouble finding this setting, go to the Extensions icon on the left panel of vscode (looks like 4 blocks) and search for Jupyter. Just under the search, on the Jupyter extension, click the gear. Scroll down to "Notebook File Root".
This settings does not apply to remote kernels.
|
38

I'm one of the developers on this extension. By default we follow the VSCode pattern of working directory as opposed to the Jupyter pattern. Meaning that we use the root of the currently open workspace folder as the current working directory for starting jupyter notebooks. That might be what is confusing you here.

To get around this you can either set cwd in your notebook code as redhatvicky mentioned or you can change the default current working directory in the following VSCode setting.

Jupyter -> Notebook File Root

Since you can change that setting per workspace you can have it always default to a specific location when working in just the workspace that contains your file.

Edit 2/16/22 New setting location

7 Comments

@YANGSULIU please mark this as the correct answer :) Then it's easier for people to find it.
what should the setting be exactly? I have ${fileDirname} and it's not working.
It seems like this setting silently fails if it doesn't like the path. For example, it doesn't seem to expand ~ to be your home directory.
This is not working for me for R Jupyter notebooks.
Setting ${fileDirname} is not working for me either. This is a seriously annoying problem...
|
6

@Ian Huff's answer is still valid, however the setting seems to have changed location since then.

Instead of "Python -> Data Science -> Notebook File Root", it's now "Jupyter -> Notebook File Root"

3 Comments

This is not a valid answer for the question
Sorry about that @AnkitSangwan. How am I supposed to share that new information concerning a previous answer (since I am not yet allowed to comment on others' answers).
After you reach a reputation of 50 you will be able to comment. Until then try to answer those questions which don't need any clarification or something.
0

Your question seems quite confusing and I am unable to post a comment. Please follow this link. As per your question, I think the issue is you need to select the correct python interpreter by CTRL+SHIFT+P and then Python: Select Interpreter to select the correct conda environment or a conda interpreter. Otherwise you can try and execute the following code to change your directory before any other command:

import os
try:
    os.chdir(os.path.join(os.getcwd(), 'path_to_folder_to_have_the_file')) # '.' if the path is to current folder
    print(os.getcwd())
except:
    pass

1 Comment

In my opinion, changing the directory like that is bad because it changes the state of your system. Once your code ir ready and you don't touch it, it will work, but it's risky for future changes or debugging. Changing the settings in VSCode or the editor you are using is much more consistent, as long as you can also commit those changes as a config file.
0

Generally you can change the working directory by using "os.chdir(NEW_PATH)"

One another Suggestion is that , You can set the location to save the image from the code itself.

Here below is the code which might help you.

from __future__ import division, print_function, unicode_literals

# Common imports
import numpy as np
import os

# to make this notebook's output stable across runs
np.random.seed(42)

# To plot pretty figures
import matplotlib.pyplot as plt

plt.rcParams['axes.labelsize'] = 14
plt.rcParams['xtick.labelsize'] = 12
plt.rcParams['ytick.labelsize'] = 12

# Where to save the figures
PROJECT_ROOT_DIR = "."
CHAPTER_ID = "decision_trees"

def image_path(fig_id):
    return os.path.join(PROJECT_ROOT_DIR, "images", CHAPTER_ID, fig_id)

def save_fig(fig_id, tight_layout=True):
    print("Saving figure", fig_id)
    if tight_layout:
        plt.tight_layout()
    print(image_path(fig_id) + ".png")
    plt.savefig(image_path(fig_id) + ".png", format='png', dpi=300)

save_fig("Fig-01-6TFG")

4 Comments

THANKS! I can achieve the same goal if I use the Absolute Path to save the file. But I want to make it certain why this happen and how i can rewrite the settings to ensure every code file can run in the correct file path.
one way to change the default directory to use for notebooks ,permanently is to change the config files. Firstly in the cmdline, type: $> ipython profile create to initialize a profile with the default configuration file. Secondly, in file ipython_notebook_config.py, uncomment and edit this line: c.NotebookApp.notebook_dir = 'Z:\\username_example\folder_that_you_whant' you can also follow the below approach : ipython notebook --notebook-dir=/path/to/specific/directory
In my opinion, changing the directory like that is bad because it changes the state of your system. Once your code ir ready and you don't touch it, it will work, but it's risky for future changes or debugging. Changing the settings in VSCode or the editor you are using is much more consistent, as long as you can also commit those changes as a config file.
If I want to change using your suggestion, in what variable can I find the project root?
-1

A manual approach might also be useful in some cases.
Open VScode's file explorer by pressing the default hotkeys:
CMD + Shift + E (on MacOS) / Ctrl + Shift + E (on Windows).

On the opened left pane you'll see a list of files, with the currently open file highlighted.
right-click on the desired file name (highlighted) and select Copy Path or Copy Relative Path, depending on your needs.

The file path is now in your clipboard, so simply press CMD + v / Ctrl + v to paste it where its required.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.