HOWTO · Python

How to Open Files in Different Directory in Python

Learn how to open a file outside Python's current working directory with an absolute path, pathlib, or a relative path, and understand how path resolution works.

On this page

Pass the file path to Python’s open() function. An absolute path identifies a file from the filesystem root; a relative path starts from the process’s current working directory (CWD). The CWD may differ from the directory containing your script. For project files, pathlib.Path makes it straightforward to build paths across operating systems.

Understand file paths and the current working directory

The CWD is the directory Python uses to resolve relative paths. It is often the directory from which you launched the program, rather than the script’s directory. Inspect it when a path does not point where you expect:

import os

print(os.getcwd())

An absolute path names a location independently of the CWD. A relative path such as data/notes.txt is interpreted beneath the CWD. If open() cannot find the resulting location, Python raises FileNotFoundError; check both the path and the CWD before changing your code.

Open a file with an absolute path

Use the full path when you know where the file is. This example creates a file at an absolute temporary path, reads it, and prints its contents:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    file_path = Path(directory) / "notes.txt"
    file_path.write_text("Meeting at 10", encoding="utf-8")
    with open(file_path, "r", encoding="utf-8") as file:
        print(file.read())

The temporary directory keeps the example independent of files already on your machine. In your program, replace it with the file’s actual location. The "r" mode reads text, and encoding="utf-8" makes the text encoding explicit. The with statement closes the file when its block ends, even if an error occurs inside the block.

On Windows, you can write a path with forward slashes, a raw string such as r"C:\Users\Ada\notes.txt", or escaped backslashes such as "C:\\Users\\Ada\\notes.txt". A backslash starts an escape only when followed by a recognized escape sequence; \n, for example, represents a newline. A raw string literal cannot end with one backslash. Building a path from components with pathlib avoids much of this string-literal bookkeeping.

Build paths with pathlib

pathlib.Path is a class for representing and combining filesystem paths. The / operator joins components using the current operating system’s path conventions. This example creates a file in a sibling directory and opens it through its absolute path:

from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as parent:
    root = Path(parent)
    current = root / "app"
    other = root / "shared"
    current.mkdir()
    other.mkdir()
    target = other / "notes.txt"
    target.write_text("Shared notes", encoding="utf-8")

    file_path = target.resolve()
    with open(file_path, "r", encoding="utf-8") as file:
        print(file.read())

For a real project, start with a known directory and add child names, as in Path("/srv/project") / "data" / "notes.txt". Use an absolute starting directory when the program must work regardless of where it was launched. Path.resolve() gives an absolute path for an existing target and can make path diagnostics clearer.

Use a relative path or change the working directory

Suppose the project contains scripts/read_notes.py and shared/notes.txt, and the CWD is project/scripts. From that CWD, ../shared/notes.txt moves up to project and then into shared. This is convenient when the launch directory is predictable, but the same relative path can refer to a different location if the program starts with another CWD. To anchor a project path to the script instead, build from Path(__file__).resolve().parent.

This runnable example creates the project layout, sets the process CWD to project/scripts, and reads the sibling file with a context manager:

import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    project = Path(directory) / "project"
    scripts = project / "scripts"
    shared = project / "shared"
    scripts.mkdir(parents=True)
    shared.mkdir()
    (shared / "notes.txt").write_text("Project notes", encoding="utf-8")

    original_directory = os.getcwd()
    try:
        os.chdir(scripts)
        with open("../shared/notes.txt", "r", encoding="utf-8") as file:
            print(file.read())
    finally:
        os.chdir(original_directory)

The relative path is resolved from the process CWD, which this example sets to project/scripts; it is not resolved from the source file’s directory.

If a program handles several files in one directory, it can change the process’s CWD and then use short relative paths. This example creates its input before changing directories and restores the original CWD afterward:

import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    target = Path(directory) / "notes.txt"
    target.write_text("Daily notes", encoding="utf-8")
    original_directory = os.getcwd()
    try:
        os.chdir(directory)
        with open("notes.txt", "r", encoding="utf-8") as file:
            print(file.read())
    finally:
        os.chdir(original_directory)

os.chdir() changes process-wide state, so it changes how relative paths in other parts of the program are resolved too. Restoring the previous directory contains that effect. For one file, passing an absolute or pathlib path is usually simpler. If access still fails, check that the process can read the file as well as verifying its location.