首页 > 解决方案 > 在 Jupyter Notebook 中使用当前文件夹之外的相对路径运行 Python 文件

问题描述

假设我有~/file_to_run.py想要~/notebooks/my_notebook.ipynb使用魔法命令从 jupyter notebook ()运行的 python 文件%run。问题是file_to_run.py使用相对路径,例如:

open('data/file.csv') # full path ~/data/file.csv

当我运行~/file_to_run.py~/notebooks/my_notebook.ipynb

%run ../file_to_run.py

我收到以下错误:

FileNotFoundError: [Errno 2] No such file or directory: 'data/file.csv'

是否可以在不修改 python 文件的情况下进行任何修复?谢谢!

标签: pythonpathjupyter-notebookjupyter

解决方案


更改工作目录可能是一个解决方案:

import os
os.chdir('../') # Change the working directory
%run file_to_run.py # Call the script from new working directory

推荐阅读