当我在VScode中使用jupyter扩展名并在jupyter中运行一行代码以使用相对路径保存文件时,我在另一个文件中找到了文件(iris_tree.dot)。就像我在另一个文件路径中调试/运行代码一样。我该如何设置Jupyter运行器的正确路径?
#%%
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
)
答案 0 :(得分:7)
答案 1 :(得分:2)
@Ian Huff 的回答仍然有效,但此后该设置似乎已更改位置。
现在不是“Python -> Data Science -> Notebook File Root”,而是“Jupyter -> Notebook File Root”
答案 2 :(得分:1)
我是此扩展程序的开发人员之一。默认情况下,我们遵循工作目录的VSCode模式,而不是Jupyter模式。这意味着我们使用当前打开的工作区文件夹的根作为启动jupyter笔记本的当前工作目录。这可能会使您感到困惑。
要解决此问题,您可以按照redhatvicky所述在笔记本代码中设置cwd,也可以在以下VSCode设置中更改默认的当前工作目录。
Python->数据科学->笔记本文件根
由于您可以更改每个工作区的设置,因此仅在包含文件的工作区中工作时,始终可以将其默认设置为特定位置。
答案 3 :(得分:0)
您的问题似乎很混乱,我无法发表评论。请遵循此link。根据您的问题,我认为问题是您需要通过 CTRL + SHIFT + P 选择正确的python解释器,然后通过Python: Select Interpreter
选择正确的conda环境或conda解释器。否则,您可以尝试执行以下代码来更改目录,然后再执行其他任何命令:
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
答案 4 :(得分:0)
通常,您可以使用“ os.chdir(NEW_PATH)”来更改工作目录
另一个建议是,您可以设置代码的位置以保存图像。
以下是可能对您有帮助的代码。
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")