Search code examples
pythonerror-handlingfilepathfile-handling

NameError: name '__file__' is not defined , os.path.dirname(os.path.abspath(__file__))


I'm trying to use os.path.dirname(os.path.abspath(file)) for tracking my file txt but i don't why its not working with me:

  import os

  print(os.getcwd()) # Get Working directory

  print(os.path.dirname(os.path.abspath(__file__)))
  file = open("Youness.txt") 

  NameError: name '__file__' is not defined.

Solution

  • There is a good chance that __ file __ is not defined because you execute your code in an interactive shell.

    Write it in a file and execute it with python and the const __ file __ will be defined.

    Hope it helps.