Back to course

Working with the File System (`os` and `pathlib`)

Python Programming: The 0 to Hero Bootcamp

Interacting with the Operating System

The os module provides functions for interacting with the operating system (e.g., creating folders, renaming files).

Essential os Functions

python import os

1. Get current working directory

current_dir = os.getcwd() print(f"Current Directory: {current_dir}")

2. Change directory

os.chdir('/temp')

3. List contents of a directory

print(os.listdir(current_dir)) # Returns a list of file/folder names

4. Creating a directory

if not os.path.exists('new_folder'): os.mkdir('new_folder') print("Folder created.")

5. Renaming/Moving files

os.rename('old_name.txt', 'new_name.txt')

6. Deleting files

os.remove('temp_file.txt')

os.rmdir('empty_folder') # Only removes empty directories

Introducing pathlib (Modern Approach)

The pathlib module (introduced in Python 3.4) offers an object-oriented way to handle file system paths, which is often cleaner and more robust than string-based os paths.

python from pathlib import Path

Create a path object

p = Path.cwd() / 'new_folder' / 'my_file.txt' print(p)

Check if it exists

print(p.exists())

Creating directories (works like mkdir -p)

Path('data/reports').mkdir(parents=True, exist_ok=True)