3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Jupyter Notebook で "NameError: name '__file__' is not defined" となる

Posted at

疑問

Jupyter Notebookで以下のコードを実行してみると...

print(os.path.dirname(__file__))

エラーがでる。

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-8-755a91d3a9c3> in <module>()
      3 > NameError: name '__file__' is not defined
      4 '''
----> 5 print(os.path.dirname(__file__))

NameError: name '__file__' is not defined

どうしてだ...?

原因

JupyterではIPython(REPL)からコードを実行しているが、この環境下だと特殊グローバル変数 __file__は設定されないらしい。

解決

代わりに以下のコードで現在のipynbの絶対パスを取得する。

os.path.abspath('')

参考

stack overflowの投稿

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?