Question

Python Current Working Directory vs Script Directory Explained

pythondirectory

Question

How can I determine the following in Python?

  • The current directory: the folder I was in when I ran the Python script from the shell
  • The directory of the Python file being executed: the folder where the script itself is stored

For example, if I run a script from one location but the .py file is saved in another, how can I get both paths correctly?

Short Answer

By the end of this page, you will understand the difference between the current working directory and a script's file location in Python. You will learn which built-in tools to use, how os.getcwd() differs from __file__, when each one matters, and how to avoid common path-related mistakes in real programs.

Concept

In Python, two path concepts are often confused:

  • Current working directory (CWD): the directory your process is currently running in
  • Script directory: the directory where the Python file is located

These are not always the same.

For example:

  • Your script may be stored in /projects/app/script.py
  • But you might run it while your shell is in /home/user

In that case:

  • The working directory is /home/user
  • The script directory is /projects/app

This distinction matters because many file operations use the current working directory by default. If your code opens a file like this:

open("data.txt")

Python looks for data.txt relative to the current working directory, not automatically relative to the script file.

How to get each one

To get the current working directory:

import os

print(os.getcwd())

To get the directory of the current script:

import os

print(os.path.dirname(os.path.abspath(__file__)))

Why this matters

Understanding this prevents bugs such as:

  • files not being found when the script is run from another folder
  • config files loading correctly on one machine but failing on another
  • relative paths behaving differently in an IDE, terminal, or scheduler

In real programming, path handling is important for scripts, web apps, automation tools, tests, and data pipelines.

Mental Model

Think of it like this:

  • The current working directory is your current location
  • The script directory is your home address

You might currently be standing in a coffee shop, but your home is somewhere else.

In the same way:

  • os.getcwd() tells you where the program is currently standing
  • __file__ tells you where the script lives

If you ask for a relative file path, Python usually interprets it from where it is standing, not from where the script lives.

That is why beginners often expect this:

open("config.json")

to load a file next to the script, but it actually loads from the current working directory unless you build the path explicitly.

Take Quiz

Syntax and Examples

Current working directory

Use os.getcwd():

import os

current_dir = os.getcwd()
print(current_dir)

This returns the directory the Python process is running in.

Script file directory

Use __file__ with os.path.abspath() and os.path.dirname():

import os

script_path = os.path.abspath(__file__)
script_dir = os.path.dirname(script_path)

print(script_path)
print(script_dir)

What each part does

  • __file__ is the script filename/path
  • os.path.abspath(__file__) converts it to an absolute path
  • os.path.dirname(...) gets the folder containing the file

Example showing the difference

import os

print("Current working directory:", os.getcwd())
print("Script directory:", os.path.dirname(os.path.abspath(__file__)))

If you run this script from a different folder, those two values may be different.

Modern alternative with pathlib

pathlib is often easier to read:

from pathlib import Path

current_dir = Path.cwd()
script_dir = Path(__file__).resolve().parent

print("Current working directory:", current_dir)
print("Script directory:", script_dir)

This is the same idea, but with a more modern path API.

Step by Step Execution

Consider this file:

import os

print("CWD:", os.getcwd())
print("SCRIPT DIR:", os.path.dirname(os.path.abspath(__file__)))

Assume:

  • the script is stored at /projects/tools/show_paths.py
  • you open a terminal in /home/user
  • you run the script with:
python /projects/tools/show_paths.py

Step by step

  1. Python starts the process from /home/user
  2. os.getcwd() checks the process working directory
  3. It returns:
/home/user
  1. __file__ refers to the script being executed
  2. os.path.abspath(__file__) becomes:
/projects/tools/show_paths.py
  1. os.path.dirname(...) removes the filename and returns:
/projects/tools

Output

CWD: /home/user
SCRIPT DIR: /projects/tools

This example shows why relative file access can be surprising if you assume the script directory and working directory are always the same.

Real World Use Cases

Loading files relative to where the user runs the program

If a command-line tool should use the caller's current location, use the working directory.

Examples:

  • searching files in the folder the user is currently in
  • writing output to the current terminal location
  • batch-processing files in the current directory

Loading resources bundled with the script

If your script ships with files stored next to it, use the script directory.

Examples:

  • config.json
  • templates
  • seed data
  • local SQLite databases

Build and automation scripts

Automation tools often need both:

  • the working directory to know where the command was launched
  • the script directory to find helper files

Web and backend apps

Applications often build paths to:

  • static files
  • environment-specific configs
  • migration files
  • logs

Using explicit paths makes deployment more reliable.

Data processing

A data script may:

  • read input files from the current directory
  • load schemas or mappings from files stored with the code
Take Quiz

Real Codebase Usage

In real projects, developers usually avoid relying on ambiguous relative paths.

Common pattern: build paths from the script location

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
config_file = BASE_DIR / "config.json"

This makes code more predictable because it does not depend on where the program was launched.

Common pattern: use the working directory for user input/output

from pathlib import Path

output_file = Path.cwd() / "report.txt"

This is useful when the output should appear in the user's current folder.

Validation pattern

Developers often check whether files exist before using them:

from pathlib import Path

config_path = Path(__file__).resolve().parent / "config.json"

if not config_path.exists():
    raise FileNotFoundError(f"Missing config file: {config_path}")

Configuration pattern

Projects sometimes define a base path once and reuse it everywhere:

from pathlib import Path

BASE_DIR = Path(__file__).resolve().parent
DATA_DIR = BASE_DIR / "data"
LOG_DIR = BASE_DIR / "logs"

This keeps path logic consistent across the codebase.

Testing pattern

Tests often fail if they depend on the working directory. A safer approach is to reference test files relative to the test file itself.

from pathlib import Path

FIXTURE_DIR = Path(__file__).resolve().parent / "fixtures"

Common Mistakes

1. Assuming relative paths are based on the script location

Broken example:

with open("config.json") as f:
    data = f.read()

This only works if config.json is in the current working directory.

Safer version:

from pathlib import Path

config_path = Path(__file__).resolve().parent / "config.json"
with open(config_path) as f:
    data = f.read()

2. Confusing os.getcwd() with the script directory

Broken assumption:

import os

script_dir = os.getcwd()  # not necessarily true

os.getcwd() tells you where the process is running, not where the script file is stored.

3. Forgetting that __file__ may not exist in some interactive environments

In some environments such as an interactive shell or notebook, __file__ may be unavailable.

Example:

print(__file__)

This can raise an error outside normal script execution.

4. Hardcoding path separators

Broken example:

path = "folder/file.txt"

or

path = "folder\\file.txt"

Safer version:

from pathlib import Path

path = Path("folder") / "file.txt"

This works across operating systems.

5. Changing the working directory without being careful

import os
os.chdir("some_folder")

Changing the working directory affects all later relative file operations. This can make debugging harder.

Avoid it unless there is a clear reason.

Comparisons

ConceptWhat it meansTypical use
os.getcwd()Current working directory of the running processUser-relative input/output
__file__Path of the current script fileFinding files stored with the script
os.path.dirname(os.path.abspath(__file__))Directory containing the scriptLoading bundled resources
Path.cwd()pathlib version of current working directoryModern path handling
Path(__file__).resolve().parentpathlib version of script directoryModern path handling

os vs pathlib

ApproachExampleNotes
osos.path.dirname(os.path.abspath(__file__))Older and very common
pathlibPath(__file__).resolve().parentCleaner and easier to read

Working directory vs script directory

QuestionUse
Where am I running from?os.getcwd() or Path.cwd()
Where is this Python file located?__file__ with os.path or pathlib
Take Quiz

Cheat Sheet

import os
from pathlib import Path

Get current working directory

os.getcwd()
Path.cwd()

Get current script path

os.path.abspath(__file__)
Path(__file__).resolve()

Get current script directory

os.path.dirname(os.path.abspath(__file__))
Path(__file__).resolve().parent

Key rule

  • Relative paths like open("file.txt") use the current working directory
  • They do not automatically use the script directory

Safe way to open a file next to the script

from pathlib import Path

file_path = Path(__file__).resolve().parent / "file.txt"
with open(file_path) as f:
    content = f.read()

Common edge case

  • __file__ may not exist in interactive shells or notebooks

Good practice

  • Use pathlib for readable cross-platform path handling
  • Use script-relative paths for bundled resources
  • Use working-directory paths for user-facing command-line behavior

FAQ

What is the difference between the current working directory and the script directory?

The current working directory is where the Python process is running. The script directory is where the .py file is stored. They can be different.

How do I get the current working directory in Python?

Use:

import os
os.getcwd()

or:

from pathlib import Path
Path.cwd()

How do I get the directory of the current Python file?

Use:

from pathlib import Path
Path(__file__).resolve().parent

Why does open("file.txt") sometimes fail?

Because Python looks for file.txt in the current working directory, not necessarily next to your script.

Is __file__ always available?

No. It usually exists in normal script execution, but not always in interactive environments like some shells or notebooks.

Should I use os.path or pathlib?

Both work. pathlib is generally easier to read and is recommended for new Python code.

Can I change the working directory in Python?

Yes, with os.chdir(), but do it carefully because it changes how all relative paths are resolved.

Take Quiz

Mini Project

Description

Create a small Python script that prints both the current working directory and the script's own directory, then safely reads a text file stored next to the script. This demonstrates the difference between process location and file location in a practical way.

Goal

Build a script that shows both path types and loads a local file reliably, even when the script is run from another directory.

Requirements

  • Print the current working directory
  • Print the absolute path of the script directory
  • Read a file named message.txt located next to the script
  • Handle the case where message.txt does not exist
Take Quiz

Keep learning

Related questions

View more