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

Question:

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.
Asked By: Error 404

||

Answers:

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.

Answered By: Romain