Kahibaro
Discord Login Register

File paths

Understanding File Paths

When you work with files in Python, you almost always need to tell Python where the file is. That “where” is called the file path.

This chapter focuses on how to:

We’ll assume you already know what a file is and how to open one with open() in general.


Absolute vs Relative Paths

A file path is a string that describes how to get to a file or folder.

Absolute paths

An absolute path tells Python exactly where a file is on your computer, starting from the “root” of the file system.

Examples:

Absolute paths:

Relative paths

A relative path is written relative to the current working directory (where your script is running from, or where your program is currently “looking”).

Examples of relative paths:

Relative paths:

When to use which

Path Separators: Windows vs macOS/Linux

Different operating systems use different symbols to separate folders in a path.

This creates a few common issues:

Problem: Backslash escapes in strings

In Python strings, \ starts an escape sequence (like \n for newline).

So this:

python
path = "C:\new_folder\data.txt"

is a problem because \n inside the string is treated as a newline.

Safer options
  1. Use double backslashes:
python
   path = "C:\\new_folder\\data.txt"
  1. Use raw strings (prefix with r):
python
   path = r"C:\new_folder\data.txt"

In a raw string, \ is treated as a normal character.

  1. Use forward slashes (Python accepts them on Windows too):
python
   path = "C:/new_folder/data.txt"

Basic Path Operations with `os` and `os.path`

To work with file paths in a cross-platform way (that works on Windows, macOS, and Linux), Python gives you the os and os.path modules.

Joining paths with `os.path.join`

Instead of manually writing "/" or "\\", let Python build paths for you:

import os
folder = "data"
filename = "numbers.txt"
path = os.path.join(folder, filename)
print(path)         # On Windows: data\numbers.txt
                    # On macOS/Linux: data/numbers.txt

os.path.join automatically uses the right separator for the operating system.

This is especially useful when:

Getting the current working directory

The current working directory is the folder Python considers “current” for relative paths.

import os
current_dir = os.getcwd()
print("Current directory:", current_dir)

This helps you understand where "data/file.txt" is relative to.

Getting a file’s directory from `__file__`

If you want to build paths relative to the script’s location, not the working directory:

import os
# Path to this script file
script_path = __file__
# Directory that contains this script
script_dir = os.path.dirname(script_path)
# A data file in a "data" folder next to the script
data_file = os.path.join(script_dir, "data", "numbers.txt")
print(data_file)

This is useful when:

Checking If Paths and Files Exist

Sometimes you need to check if a file or folder exists before using it.

Check if a path exists

import os
path = "data/numbers.txt"
if os.path.exists(path):
    print("Path exists!")
else:
    print("Path does not exist.")

Check if it’s a file or a directory

import os
path = "data"
if os.path.isdir(path):
    print("It's a directory.")
elif os.path.isfile(path):
    print("It's a file.")
else:
    print("It doesn't exist.")

Absolute Paths in Python

You can convert a relative path into an absolute path.

import os
relative_path = "data/numbers.txt"
absolute_path = os.path.abspath(relative_path)
print("Relative:", relative_path)
print("Absolute:", absolute_path)

This is useful for debugging: you can see exactly where Python is looking.


Using `pathlib` (Modern Path Handling)

Python also provides a newer module, pathlib, which represents paths as objects instead of plain strings. This can make your code cleaner and easier to work with.

Creating `Path` objects

from pathlib import Path
# Current directory
current_dir = Path.cwd()
print(current_dir)
# Path to a file in a "data" subfolder
data_file = current_dir / "data" / "numbers.txt"
print(data_file)

The / operator is overloaded to mean “join these path parts”.

Common `Path` methods

from pathlib import Path
path = Path("data") / "numbers.txt"
print(path.exists())   # True or False
print(path.is_file())  # True or False
print(path.is_dir())   # True or False (likely False here)
# Absolute version
print(path.resolve())

You can also open files using Path objects:

from pathlib import Path
path = Path("data") / "numbers.txt"
with path.open() as f:
    content = f.read()
    print(content)

Special Parts in Paths: `.`, `..`, and Home Directory

Paths can contain short-cuts:

Examples:

With pathlib:

from pathlib import Path
current_dir = Path.cwd()
parent_dir = current_dir.parent
print("Current:", current_dir)
print("Parent :", parent_dir)

Home directory (`~`)

Most systems have a “home” directory for each user. Many tools use ~ to mean “home”.

pathlib can find it directly:

from pathlib import Path
home = Path.home()
print("Home directory:", home)
# A file on the desktop (example, may differ by OS)
desktop_file = home / "Desktop" / "notes.txt"
print(desktop_file)

Note: The exact desktop folder name or location can vary.


Common Path-Related Mistakes (and How to Avoid Them)

1. Wrong slashes or escape sequences

Bad:

python
path = "C:\new_folder\data.txt"   # \n is a newline

Better:

python
path = r"C:\new_folder\data.txt"
# or
path = "C:/new_folder/data.txt"

2. Assuming the current working directory

If you use a relative path, but run your script from a different folder, it may fail to find files.

Avoid:

python
file = open("data/numbers.txt")   # Might fail if run from another directory

More reliable (relative to script location):

import os
script_dir = os.path.dirname(__file__)
path = os.path.join(script_dir, "data", "numbers.txt")
with open(path) as f:
    content = f.read()

Or with pathlib:

from pathlib import Path
script_dir = Path(__file__).parent
path = script_dir / "data" / "numbers.txt"
with path.open() as f:
    content = f.read()

3. Hard-coding OS-specific paths

Avoid writing code that only works on one OS:

python
path = "C:\\Users\\Alice\\Documents\\file.txt"

Prefer:

from pathlib import Path
home = Path.home()
path = home / "Documents" / "file.txt"

This way, it adapts to different systems.


Summary

In this chapter, you learned:

With a solid understanding of file paths, you can now control where your Python programs read and write files, which is essential for building reliable file-based programs.

Views: 14

Comments

Please login to add a comment.

Don't have an account? Register now!