python - 在 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 文件的情况下进行任何修复?谢谢!
解决方案
更改工作目录可能是一个解决方案:
import os
os.chdir('../') # Change the working directory
%run file_to_run.py # Call the script from new working directory
推荐阅读
- react-native - 如何在 React Native 中创建可重用的 Modal
- c# - 如何从 Powershell 调用 Win32 API 函数?
- solr - TYPO3 solr 扩展不索引
- gnuplot - Gnuplot 中的可变线条颜色
- swift - 点击 UITextField 的清除按钮调用 keyboardWillHide()
- javascript - 使用 java 脚本对具有日期和时间的大量数组数据进行排序
- python - Python-Swift 互操作(PythonKit):更改默认标准输入编码
- c# - 试图将 XML 字符串解析为 c# 对象但没有成功
- python - 如何从 postgreSQL WHERE key="1" 中选择 json 数据?
- python - 姜戈。如何将正确的变量分配给预填充表单