Last modified: Feb 06, 2026 By Alexander Williams

Python __file__ Attribute Guide & Examples

Python is full of special attributes. One of the most useful is __file__. This attribute holds the path to the current Python file.

It is a built-in attribute for modules. You can use it to find where your script lives on the computer.

This guide explains what __file__ is. You will learn how to use it correctly. We will also cover common pitfalls and solutions.

What is the __file__ Attribute?

The __file__ attribute is a string. It contains the file system path of the module where it is used.

If you run a script directly, __file__ gives the full path to that script. For imported modules, it gives the path to the module's .py file.

This is incredibly useful for tasks that depend on the file's location. For example, you might need to read a configuration file stored in the same folder.

Basic Usage of __file__

Using __file__ is simple. Just print it or assign it to a variable. Let's look at a basic example.

Create a file named script.py with the following code.


# script.py
print(f"The path of this file is: {__file__}")
    

Now, run this script from your terminal. If you need a refresher on how to run a Python file in terminal, check out our guide.


$ python /path/to/your/script.py
    

The output will show the absolute path to your script.py file.


The path of this file is: /path/to/your/script.py
    

Getting the Directory and File Name

Often, you don't need the full file path. You might just need the directory or the filename. Python's os.path module helps with this.

You can use os.path.dirname() to get the directory. Use os.path.basename() to get just the filename.


# script.py
import os

file_path = __file__
directory = os.path.dirname(file_path)
filename = os.path.basename(file_path)

print(f"Full Path: {file_path}")
print(f"Directory: {directory}")
print(f"Filename: {filename}")
    

Full Path: /home/user/projects/script.py
Directory: /home/user/projects
Filename: script.py
    

Building Dynamic File Paths

The real power of __file__ is building paths to other files. This makes your script portable. It will work no matter where it is installed.

Imagine you have a data file named config.json in the same folder as your script. You can build a path to it like this.


# script.py
import os

# Get the directory of the current script
script_dir = os.path.dirname(__file__)

# Build a path to a config file in the same directory
config_path = os.path.join(script_dir, 'config.json')

print(f"Config file should be at: {config_path}")

# Now you can safely open the file
# with open(config_path, 'r') as f:
#     data = f.read()
    

This method is much safer than using hard-coded paths. Your script won't break if you move it to a new folder.

Common Error: __file__ Not Defined

Beginners often encounter an error: NameError: name '__file__' is not defined. This happens in specific environments.

The __file__ attribute is only defined for modules loaded from a file. It is not defined in two main cases.

First, when you run code in an interactive Python shell (like IDLE or a REPL). Second, when a module is frozen into a standalone executable.

Here is an example of the error.


# This will cause an error in an interactive shell
>>> print(__file__)
Traceback (most recent call last):
  File "", line 1, in 
NameError: name '__file__' is not defined
    

How to Handle the Missing __file__

You should write your code defensively. Always check if __file__ exists before using it. Use a try-except block or check with hasattr().


# script.py
import os

try:
    current_file = __file__
except NameError:
    # Handle the case where __file__ is not defined
    print("Warning: __file__ is not available. Using current working directory.")
    current_file = os.getcwd() # Fallback to current directory

print(f"Base path is: {current_file}")
    

Another common approach is to use sys.argv[0]. This contains the script name used to invoke the interpreter. However, its value can be less reliable than __file__ in some scenarios.

__file__ in Imported Modules

When you import a module, its __file__ attribute points to its own location. This is different from the main script's location.

This is useful for package development. A module can find its own data files relative to itself.

Create two files: main.py and a module mymodule.py.


# mymodule.py
import os

def get_module_path():
    """Returns the directory this module is in."""
    return os.path.dirname(__file__)
    

# main.py
import mymodule
import os

print(f"Main script file: {__file__}")
print(f"Module directory: {mymodule.get_module_path()}")

# Build a path to a file inside the module's directory
module_data_path = os.path.join(mymodule.get_module_path(), 'data.txt')
print(f"Path to module data: {module_data_path}")
    

Absolute vs. Relative Paths

The value of __file__ can be absolute or relative. It depends on how the script was run.

If you run the script with an absolute path, __file__ will be absolute. If you run it with a relative path (like python ./script.py), it might be relative.

For robust code, you should convert it to an absolute path using os.path.abspath().


import os

# Convert __file__ to an absolute path
absolute_path = os.path.abspath(__file__)
print(f"Absolute file path: {absolute_path}")
    

This ensures your path operations are predictable and consistent.

Practical Example: Loading a Resource

Let's combine everything into a practical example. We'll write a function that loads a text file from a data folder next to the script.


# resource_loader.py
import os

def load_local_data(filename):
    """
    Loads a file from a 'data' folder located in the same
    directory as this script.
    """
    # Get the directory this script is in
    script_dir = os.path.dirname(os.path.abspath(__file__))
    
    # Build the path to the data folder and the target file
    data_dir = os.path.join(script_dir, 'data')
    file_path = os.path.join(data_dir, filename)
    
    # Check if the file exists
    if not os.path.exists(file_path):
        raise FileNotFoundError(f"Data file not found: {file_path}")
    
    # Read and return the file contents
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()

# Example usage
if __name__ == "__main__":
    try:
        content = load_local_data('example.txt')
        print("File content loaded successfully:")
        print(content)
    except FileNotFoundError as e:
        print(f"Error: {e}")
    

This pattern is common in applications, games, and tools. It keeps resources neatly bundled with the code.

Conclusion

The Python __file__ attribute is a simple but powerful tool. It provides the file system path of the current module.

You learned its basic use, how to extract directory and filename, and how to build dynamic paths. We covered the crucial error when __file__ is not defined and how to handle it.

Remember to use os.path.abspath() for robustness. Always check for the attribute's existence in shared code.

Mastering __file__ helps you write portable, reliable Python scripts. Your code will work correctly regardless of where it is executed. This is a key skill for any Python developer building real-world applications.