Problem Solving: NameError: name '__file__' is not defined

Today the command line you want to use os.path.dirnameencounter this problem when you view the file path:

>>> import os
>>> print(os.path.dirname(__file__))

Error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined

Cause:
If in an interactive environment, it will burst exception. Because at this time __file__it did not generate.


Make up the basics:

  1. __file__ path to the current script is running. But it also points to different situations.
    • If you execute the command using an absolute path, __ file__ absolute path is the script.
    • If you are using a relative path, __ file__ is a relative path to the script.
  2. os.path.dirname ()
    os.path.dirname (path) Returns the directory path of.
Published 673 original articles · won praise 644 · views 380 000 +

Guess you like

Origin blog.csdn.net/zhaohaibo_/article/details/103816033