Python File Paths
Table of Contents
In the last lesson, we learned about Python Working with JSON Files. After learning how to read and write files, let us learn about file paths in Python. A file path tells Python where a file is on our computer.
In this tutorial, we will learn about absolute paths, relative paths, and how to work with paths using os.path and pathlib.
What Is a File Path in Python?
A file path is the address of a file. It tells us where the file is located.
There are two types of paths.
Absolute path β the full address from the root of the file system.
On Windows:
C:\Users\Alex\Documents\file.txtOn Mac or Linux:
/home/alex/documents/file.txtRelative path β the address relative to where our program is running.
data/file.txtThat means βlook in the data folder next to our script.β
Why Do File Paths Matter in Python?
When we open a file, Python needs to know where to find it. If we just write open("file.txt"), Python looks in the current working directory.
If the file is somewhere else, we need to give a path.
The Current Working Directory in Python
The current working directory is the folder where Python is running. We can check it with os.getcwd().
import os
print(os.getcwd())Output
/home/alex/projectsThat tells us where Python is looking when we use a relative path.
How to Open a File with an Absolute Path in Python
We can use an absolute path to open a file.
with open("/home/alex/documents/file.txt", "r") as file: content = file.read()On Windows, we use backslashes. But backslashes are special in Python. So we use raw strings.
with open(r"C:\Users\Alex\Documents\file.txt", "r") as file: content = file.read()The r before the string means βraw string.β It tells Python not to treat backslashes as escape characters.
Or we can use forward slashes. Python handles them on Windows too.
with open("C:/Users/Alex/Documents/file.txt", "r") as file: content = file.read()How to Open a File with a Relative Path in Python
A relative path is relative to the current working directory.
with open("data/file.txt", "r") as file: content = file.read()This looks for a folder called data in the current directory, and then a file called file.txt inside it.
We can also go up a level using ...
with open("../file.txt", "r") as file: content = file.read()That means βgo up one folder, then find file.txt.β
How to Join Paths with os.path.join() in Python
Hardcoding paths with slashes is not portable. On Windows, we use backslashes. On Mac and Linux, we use forward slashes.
To make our code work on all systems, we use os.path.join().
import os
folder = "data"filename = "file.txt"path = os.path.join(folder, filename)print(path)On Windows, the output is:
data\file.txtOn Mac or Linux, the output is:
data/file.txtSo our code works everywhere.
How to Use pathlib for Modern Path Handling in Python
Python 3.4 introduced pathlib. It is a more modern way to work with paths.
from pathlib import Path
path = Path("data") / "file.txt"print(path)Output
data/file.txtpathlib handles paths in an object-oriented way. It works on all systems.
We can check if a file exists.
from pathlib import Path
path = Path("data/file.txt")if path.exists(): print("File exists")else: print("File not found")We can read a file.
from pathlib import Path
path = Path("data/file.txt")content = path.read_text()print(content)We can write to a file.
from pathlib import Path
path = Path("output.txt")path.write_text("Hello, world!")pathlib is very convenient. Many Python programmers prefer it over os.path.
Python File Path Example β Reading a File from a Folder
Letβs build a program that reads a file from a specific folder.
import os
folder = "data"filename = "names.txt"path = os.path.join(folder, filename)
try: with open(path, "r") as file: for line in file: print(line.strip())except FileNotFoundError: print(f"File not found: {path}")That is portable and clean.
Another Example β Creating a Folder and Writing a File in Python
import os
folder = "output"if not os.path.exists(folder): os.makedirs(folder)
filepath = os.path.join(folder, "result.txt")with open(filepath, "w") as file: file.write("Hello, world!")That creates the folder if it does not exist, then writes a file inside it.
Common Mistakes with File Paths in Python
Mistake 1: Using backslashes without raw strings
with open("C:\Users\Alex\file.txt", "r") as file: content = file.read()In Python, \U starts an escape sequence. So this gives an error.
Fix: Use a raw string or forward slashes.
with open(r"C:\Users\Alex\file.txt", "r") as file: content = file.read()Or:
with open("C:/Users/Alex/file.txt", "r") as file: content = file.read()Mistake 2: Assuming the current directory
with open("file.txt", "r") as file: content = file.read()This only works if file.txt is in the current working directory. If our script is run from somewhere else, it will not find the file.
Fix: Use an absolute path or a path relative to the script location.
import osscript_dir = os.path.dirname(os.path.abspath(__file__))path = os.path.join(script_dir, "file.txt")Mistake 3: Not creating folders before writing
with open("data/output.txt", "w") as file: file.write("Hello")If the data folder does not exist, this gives an error.
Fix: Create the folder first.
import osos.makedirs("data", exist_ok=True)Next, we will learn Python Context Managers, which make opening and closing files cleaner and safer.