KAHIBARO Bookshelves
Discord Login Register

10.4. 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:

  • Understand different types of file paths
  • Work with paths on different operating systems
  • Use paths safely in Python code

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:

  • Windows:
    • C:\Users\Alice\Documents\report.txt
  • macOS / Linux:
    • /home/alice/report.txt
    • /Users/alice/Documents/report.txt

Absolute paths:

  • Always start from the top-level directory (C:\ on Windows, / on macOS/Linux)
  • Point to the same location no matter where your Python script is running

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:

  • "report.txt" (file in the current directory)
  • "data/report.txt" (file in a subfolder called data)
  • "../report.txt" (file in the parent folder)

Relative paths:

  • Are shorter and easier to move between computers
  • Depend on where your program is running from (the “current directory”)

When to use which

  • Use absolute paths when:
    • You need a fixed location (e.g. a shared folder)
  • Use relative paths when:
    • Your files are part of your project (e.g. a data folder next to your script)
    • You plan to move the whole project to another computer

Path Separators: Windows vs macOS/Linux

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

  • Windows: backslash \
    • Example: C:\Users\Alice\Documents\file.txt
  • macOS/Linux: forward slash /
    • Example: /home/alice/file.txt

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:

  • You want your code to run on different OSes
  • You’re building paths step-by-step

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:

  • Your script and data live together in a project folder
  • You don’t want to depend on where the script is run from

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:

  • . means “current directory”
  • .. means “parent directory” (one level up)

Examples:

  • "./data/file.txt" → file in data inside the current directory
  • "../file.txt" → file in the parent directory

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:

  • The difference between absolute and relative file paths
  • How path separators differ on Windows and macOS/Linux
  • How to use os.path to:
    • Join path parts (os.path.join)
    • Get the current working directory (os.getcwd)
    • Check if files or folders exist (os.path.exists)
  • How to use pathlib and Path objects for modern, cleaner path handling
  • How to avoid common mistakes with file paths

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: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms