[Solved] python NameError: global name ‘__file__’ is not defined

When I run this code in python 2.7, I get this error:

Traceback (most recent call last):
File "", line 30, in <module>
    long_description = read('README.txt'),
  File "", line 19, in read
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
NameError: global name '__file__' is not defined

code is:

import os
from setuptools import setup

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

    maintainer='William E. Hart',
    maintainer_email='[email protected]',
    url = '',
    license = 'BSD',
    platforms = ["any"],
    description = 'PyUtilib utilites for managing subprocesses.',
    long_description = read('README.txt'),
    classifiers = [
        'Development Status :: 4 - Beta',
        'Intended Audience :: End Users/Desktop',
        'License :: OSI Approved :: BSD License',
        'Natural Language :: English',
        'Operating System :: Microsoft :: Windows',
        'Operating System :: Unix',
        'Programming Language :: Python',
        'Programming Language :: Unix Shell',
        'Topic :: Scientific/Engineering :: Mathematics',
        'Topic :: Software Development :: Libraries :: Python Modules'],
      packages=['pyutilib', 'pyutilib.subprocess', 'pyutilib.subprocess.tests'],
      install_requires=['pyutilib.common', '']

Solution #1:

This error comes when you append this line os.path.join(os.path.dirname(__file__)) in python interactive shell.

Python Shell doesn’t detect current file path in __file__ and it’s related to your filepath in which you added this line

So you should write this line os.path.join(os.path.dirname(__file__)) in and then run python, It works because it takes your filepath.

Respondent: Nilesh

Solution #2:

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

When using your script from the console or as an application, the functions hereunder will deliver you the “execution path”, not the “actual file path”:



Your old line (initial question):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Substitute your line of code with the following snippet.

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it’s data/configuration files.

Tested with python:

  • 3.3.4
  • 2.7.13
Respondent: Kwuite

Solution #3:

change your codes as follows! it works for me.

Respondent: Jojo Josiane

Solution #4:

I’ve run into cases where __file__ doesn’t work as expected. But the following hasn’t failed me so far:

import inspect
src_file_path = inspect.getfile(lambda: None)

This is the closest thing to a Python analog to C’s __FILE__.

The behavior of Python’s __file__ is much different than C’s __FILE__. The C version will give you the original path of the source file. This is useful in logging errors and knowing which source file has the bug.

Python’s __file__ only gives you the name of the currently executing file, which may not be very useful in log output.

Respondent: Todd

Solution #5:

If all you are looking for is to get your current working directory os.getcwd() will give you the same thing as os.path.dirname(__file__) as long as you have not changed the working directory elsewhere in your code. os.getcwd() also works in interactive mode.


Respondent: Andrew Fallgren

Solution #6:

Are you using the interactive interpreter? You can use


You should read: How do I get the path of the current executed file in Python?

Respondent: Eloims

Solution #7:

You will get this if you are running the commands from the python shell:

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

You need to execute the file directly, by passing it in as an argument to the python command:

$ python

In your case, it should really be python install

Respondent: Burhan Khalid

Solution #8:

If you’re exec’ing a file via command line, you can use this hack

import traceback

def get_this_filename():
        raise NotImplementedError("No error")
    except Exception as e:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        filename = traceback.extract_tb(exc_traceback)[-1].filename
    return filename

This worked for me in the UnrealEnginePython console, calling py.exec

Respondent: crizCraig

Solution #9:

I’m having exacty the same problem and using probably the same tutorial. The function definition:

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

is buggy, since os.path.dirname(__file__) will not return what you need. Try replacing os.path.dirname(__file__) with os.path.dirname(os.path.abspath(__file__)):

def read(*rnames):
    return open(os.path.join(os.path.dirname(os.path.abspath(__file__)), *rnames)).read()

I’ve just posted Andrew that the code snippet in current docs don’t work, hopefully, it’ll be corrected.

Respondent: ducin

Solution #10:

if you are using jupyter notebook like:

MODEL_NAME = os.path.basename(file)[:-3]

NameError                                 Traceback (most recent call last)
<ipython-input-10-f391bbbab00d> in <module>
----> 1 MODEL_NAME = os.path.basename(__file__)[:-3]

NameError: name '__file__' is not defined

you should place a ‘ ! ‘ in front like this

!MODEL_NAME = os.path.basename(__file__)[:-3]

/bin/bash: -c: line 0: syntax error near unexpected token `('
/bin/bash: -c: line 0: `MODEL_NAME = os.path.basename(__file__)[:-3]'


Respondent: Oscar Rangel

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy