The File System (OS & Pathlib)
Learn how to interact with your operating system to manage files and directories.
Learning Objectives
- Understand the role of the OS module
- Manage directories (create, list, delete)
- Work with paths using pathlib
- Build scripts that automate file management
Communicating with the OS
So far, we’ve only modified data inside our scripts. But Python is world-famous for Automation. To automate tasks, we need to interact with the Operating System (OS).
The os Module
The classic module for interacting with files and folders.
|
|
The pathlib Module (Modern Way)
While os is powerful, the newer pathlib module treats paths as objects, making them much easier and safer to use.
|
|
Automation Task
Professional developers often use these modules to organize thousands of files at once (e.g., “Move all .jpg files to a folder called Photos”).
Interactive Practice
Try writing a script that creates a folder called Project_Data and then creates a blank file inside it called log.txt.
| Task | OS Module | Pathlib |
|---|---|---|
| Get CWD | os.getcwd() |
Path.cwd() |
| Join Path | os.path.join(a, b) |
a / b |
| Create Dir | os.mkdir('x') |
Path('x').mkdir() |
Quiz
Complete this quiz with a minimum score of 80% to mark Day 23 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!