File Paths and Directory Operations
Learn to work with file paths, check existence, and manage directories
File Paths and Directory Operations
Understanding File Paths
A file path is like an address that tells Python where to find a file on your computer.
Two types of paths:
-
Absolute path - Full address from root
- Windows: C:/Users/John/Documents/data.txt
- Mac/Linux: /home/john/documents/data.txt
-
Relative path - Address from current location
- data.txt (same folder as program)
- files/data.txt (in files subfolder)
- ../data.txt (in parent folder)
The os Module
Python's os module helps you work with files and folders.
import osWhat this does: Imports the os module so you can use its functions.
Checking if File Exists
Before reading a file, check if it exists to avoid errors.
import os
if os.path.exists("data.txt"):
print("File exists")
else:
print("File not found")What this does: Checks if data.txt exists before trying to open it.
Checking if Path is File or Folder
import os
path = "data.txt"
if os.path.isfile(path):
print("This is a file")
elif os.path.isdir(path):
print("This is a folder")
else:
print("Path doesn't exist")What these do:
- isfile() returns True if path is a file
- isdir() returns True if path is a directory (folder)
Getting Current Directory
Find out where your program is running from.
import os
current = os.getcwd()
print("Current directory:", current)What getcwd() does: Gets Current Working Directory - the folder your program is running in.
Listing Files in Directory
See all files and folders in a directory.
import os
files = os.listdir()
print(files)What this shows: List of all files and folders in current directory.
List files in specific folder:
files = os.listdir("documents")
print(files)Filtering by File Type
import os
all_files = os.listdir()
txt_files = [f for f in all_files if f.endswith(".txt")]
print("Text files:", txt_files)What this does: Shows only files that end with .txt extension.
Creating Directories
Make new folders using mkdir() or makedirs().
Create Single Directory
import os
os.mkdir("new_folder")
print("Folder created")What this does: Creates a new folder named new_folder.
Note: If folder already exists, you get an error.
Create Nested Directories
import os
os.makedirs("data/reports/2024")
print("Folders created")What this does: Creates data folder, then reports inside it, then 2024 inside reports. Creates all needed folders at once.
Safe Directory Creation
import os
folder = "my_data"
if not os.path.exists(folder):
os.mkdir(folder)
print("Folder created")
else:
print("Folder already exists")Why this is better: Checks first, so no error if folder exists.
Getting File Information
File Size
import os
size = os.path.getsize("data.txt")
print("File size:", size, "bytes")What this shows: Size of the file in bytes.
Convert to KB or MB:
size_kb = size / 1024
size_mb = size / (1024 * 1024)
print("Size in KB:", size_kb)
print("Size in MB:", size_mb)Last Modified Time
import os
import time
mod_time = os.path.getmtime("data.txt")
readable = time.ctime(mod_time)
print("Last modified:", readable)What this shows: When the file was last changed.
Working with Paths
Joining Paths
Use os.path.join() to build paths correctly for any operating system.
import os
path = os.path.join("data", "reports", "file.txt")
print(path)Why use join(): Windows uses backslash, Mac/Linux use forward slash. join() handles this automatically.
Getting File Name and Extension
import os
path = "data/reports/sales.txt"
filename = os.path.basename(path)
print("File name:", filename)
folder = os.path.dirname(path)
print("Folder:", folder)
name, ext = os.path.splitext(filename)
print("Name:", name)
print("Extension:", ext)What these show:
- basename: sales.txt
- dirname: data/reports
- splitext: name=sales, ext=.txt
Getting Absolute Path
import os
relative = "data.txt"
absolute = os.path.abspath(relative)
print("Absolute path:", absolute)What this does: Converts relative path to full absolute path.
Renaming and Deleting
Renaming Files
import os
os.rename("old_name.txt", "new_name.txt")
print("File renamed")What this does: Changes file name from old_name.txt to new_name.txt.
Deleting Files
import os
if os.path.exists("temp.txt"):
os.remove("temp.txt")
print("File deleted")What this does: Deletes temp.txt if it exists.
Warning: Be careful with remove() - deleted files cannot be recovered!
Deleting Empty Directories
import os
os.rmdir("empty_folder")
print("Folder deleted")Note: rmdir() only works on empty folders.
The pathlib Module (Modern Approach)
Python 3.4+ has a newer, easier way to work with paths.
from pathlib import Path
path = Path("data.txt")
if path.exists():
print("File exists")
print("Size:", path.stat().st_size, "bytes")
print("Is file:", path.is_file())Why pathlib is nice: Uses object-oriented approach, cleaner syntax, easier to read.
Creating Paths with pathlib
from pathlib import Path
path = Path("data") / "reports" / "2024" / "sales.txt"
print(path)What this does: Uses / operator to join path parts. Very readable!
Practice Example
The scenario: You're building a file organizer that sorts files by extension into folders.
import os
current_folder = os.getcwd()
print("Organizing files in:", current_folder)
files = os.listdir()
file_count = 0
for item in files:
if os.path.isfile(item):
file_count = file_count + 1
name, ext = os.path.splitext(item)
if ext:
ext_folder = ext[1:]
if not os.path.exists(ext_folder):
os.mkdir(ext_folder)
print("Created folder:", ext_folder)
size = os.path.getsize(item)
size_kb = size / 1024
print("File:", item, "Size:", str(round(size_kb, 2)) + " KB")
print("Total files found:", file_count)What this program does:
- Gets current directory path
- Lists all items in current folder
- Checks each item if it's a file
- Gets file extension
- Creates folder for that extension if needed
- Shows file name and size in KB
- Counts total files processed
Note: This example shows how the code works but doesn't actually move files to avoid changing your system.
Key Points to Remember
Use os.path.exists() to check if file exists before accessing it. Use isfile() and isdir() to check if path is file or folder.
os.listdir() shows all files and folders in a directory. Filter results using list comprehension.
Use os.mkdir() for single folder, makedirs() for nested folders. Check existence first to avoid errors.
os.path.join() builds paths correctly for any operating system. Always use it instead of manually combining strings.
pathlib module (Path) is the modern, cleaner way to work with paths in Python 3.4 and newer.
Common Mistakes
Mistake 1: Wrong path separators
path = "data\\reports\\file.txt" # Doesn't work on Mac/Linux
path = os.path.join("data", "reports", "file.txt") # Works everywhereMistake 2: Forgetting to check existence
os.remove("file.txt") # Error if file doesn't exist!Fix:
if os.path.exists("file.txt"):
os.remove("file.txt")Mistake 3: Trying to delete non-empty folder
os.rmdir("folder") # Error if folder has files!Mistake 4: Not using absolute paths
with open("data.txt", "r") as file: # Where is data.txt?Better:
path = os.path.join(os.getcwd(), "data.txt")
with open(path, "r") as file:What's Next?
You now know how to work with files, paths, and directories. Next, you'll learn about error handling with try-except - how to handle problems in your code gracefully without crashing.