We use operating system paths to find and organize files and folders on a computer. Working with paths helps your program find files no matter where it runs.
0
0
Working with operating system paths in Python
Introduction
When you want to open a file in your program by giving its location.
When you need to join folder names and file names to make a full path.
When you want to check if a file or folder exists before using it.
When you want to get the folder part or the file part from a full path.
When you want your program to work on different computers with different path styles.
Syntax
Python
import os # Join parts of a path full_path = os.path.join('folder', 'subfolder', 'file.txt') # Get folder name from path folder = os.path.dirname(full_path) # Get file name from path file = os.path.basename(full_path) # Check if path exists exists = os.path.exists(full_path)
Use os.path.join() to combine parts safely, so it works on Windows and Mac/Linux.
os.path has many useful functions to work with paths without errors.
Examples
This joins folder names and a file name into one path.
Python
import os path = os.path.join('home', 'user', 'notes.txt') print(path)
This gets the folder part from a full path.
Python
import os path = '/home/user/notes.txt' folder = os.path.dirname(path) print(folder)
This gets the file name from a full path.
Python
import os path = '/home/user/notes.txt' file = os.path.basename(path) print(file)
This checks if the file or folder exists at the given path.
Python
import os path = 'somefile.txt' print(os.path.exists(path))
Sample Program
This program shows how to join parts into a path, get folder and file names, and check if the path exists.
Python
import os folder = 'documents' subfolder = 'projects' filename = 'report.txt' # Create full path full_path = os.path.join(folder, subfolder, filename) print(f'Full path: {full_path}') # Get folder and file parts folder_part = os.path.dirname(full_path) file_part = os.path.basename(full_path) print(f'Folder part: {folder_part}') print(f'File part: {file_part}') # Check if path exists exists = os.path.exists(full_path) print(f'Does the path exist? {exists}')
OutputSuccess
Important Notes
Paths look different on Windows (using backslashes) and Mac/Linux (using slashes), but os.path.join() handles this for you.
Always use os.path functions instead of string operations to avoid mistakes.
Summary
Use os.path.join() to build paths safely.
Use os.path.dirname() and os.path.basename() to get folder and file names.
Use os.path.exists() to check if a path is real on the computer.