Python
scripting
file path
directories
duplicates

How can I find script's directory?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Finding the directory that contains a script is a common need when loading companion files, writing logs relative to the script, or resolving configuration paths. The correct approach depends on the runtime: a normal Python script, a shell script, a notebook, or a packaged executable all behave differently. For standard Python scripts, the clean modern answer is usually based on __file__ and pathlib.

Python: The Usual Answer with pathlib

For a normal Python script file, use __file__ and resolve it to an absolute path.

python
1from pathlib import Path
2
3SCRIPT_DIR = Path(__file__).resolve().parent
4print(SCRIPT_DIR)

This gives the directory containing the script file, even when the script was launched from a different current working directory.

Why Not Use the Current Working Directory

Many beginners accidentally use os.getcwd() and then wonder why the result changes depending on where the script was launched from.

python
1import os
2
3print("cwd:", os.getcwd())
4print("script dir:", os.path.dirname(os.path.abspath(__file__)))

The current working directory is where the process was started. The script directory is where the script file lives. Those are often different and should not be confused.

os.path Equivalent

If you are working in older code that does not use pathlib, the classic approach is:

python
1import os
2
3script_dir = os.path.dirname(os.path.abspath(__file__))
4print(script_dir)

This is still valid. pathlib is usually preferred now because it is more readable and composable.

Build Paths Relative to the Script

Once you have the script directory, build related paths from it rather than assuming a fixed working directory.

python
1from pathlib import Path
2
3script_dir = Path(__file__).resolve().parent
4config_path = script_dir / "config" / "settings.json"
5
6print(config_path)

This pattern makes scripts more portable and much easier to run from CI, cron, or other launch contexts.

Bash Script Equivalent

If the question applies to shell scripts rather than Python, the common Bash answer uses BASH_SOURCE.

bash
1#!/usr/bin/env bash
2set -euo pipefail
3
4SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
5echo "$SCRIPT_DIR"

This is useful when a shell script needs to find sibling files reliably regardless of the current directory.

Sometimes the script is invoked through a symbolic link. Path(__file__).resolve() resolves symlinks to the real path, which is usually what you want for file loading.

If you need the symlink path rather than the resolved path, do not call resolve(). That difference matters in wrapper-script setups.

Interactive and Notebook Caveat

__file__ does not exist in all environments. In interactive Python sessions and many notebook contexts, it is undefined.

python
1try:
2    from pathlib import Path
3    print(Path(__file__).resolve().parent)
4except NameError:
5    print("No __file__ in this environment")

In notebooks, you often need a different convention, such as using the current working directory or passing the desired base path explicitly.

Packaged and Frozen Applications

If the program is bundled with PyInstaller or a similar tool, resource lookup may need extra handling. The executable may not behave like a normal source script, and file layout assumptions can change.

In those cases, script-directory logic should be abstracted behind one helper rather than duplicated throughout the codebase.

Practical Helper Function

If you need this behavior in multiple places, define one helper:

python
1from pathlib import Path
2
3def get_script_dir() -> Path:
4    return Path(__file__).resolve().parent
5
6if __name__ == "__main__":
7    print(get_script_dir())

Keeping the logic in one place makes it easier to adapt later for packaged environments.

Common Pitfalls

  • Using os.getcwd() when you actually need the script location.
  • Forgetting that __file__ is unavailable in some interactive environments.
  • Hardcoding relative paths instead of building them from the script directory.
  • Ignoring symlink behavior when the launch path is indirect.
  • Mixing shell and Python solutions without being explicit about runtime context.

Summary

  • For normal Python scripts, use Path(__file__).resolve().parent.
  • Use os.path.abspath(__file__) only when working in older style code.
  • Do not confuse the current working directory with the script directory.
  • Build sibling file paths relative to the script directory for portability.
  • Be aware that notebooks and packaged apps may require different handling.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.