Python Lesson: os Module
Objective
Learn how to interact with the operating system using Python's os module: reading, creating, modifying
directories and files, and more.
What is the os module?
The os module in Python provides a way to interact with the operating system. It lets you:
- Navigate directories
- Manage files and folders
- Run system commands
To use it, you must import it:
import os
1. Working with the Current Directory
import os
print("Current Directory:", [Link]())
[Link]() returns the path of the directory where your script is running.
2. Changing Directories
[Link]("/path/to/folder")
print("Changed to:", [Link]())
3. Listing Files and Folders
items = [Link]()
print("Files and Folders:", items)
4. Creating and Removing Folders
Python Lesson: os Module
[Link]("new_folder")
[Link]("new_folder")
5. Creating Nested Folders
[Link]("parent_folder/child_folder")
6. Renaming and Deleting Files
[Link]("[Link]", "[Link]")
[Link]("[Link]")
7. Checking Path and File Info
[Link]("[Link]")
[Link]("[Link]")
[Link]("folder")
8. Running System Commands
[Link]("echo Hello from the terminal!")
Practice Example
import os
[Link]("TestFolder")
[Link]("TestFolder")
with open("[Link]", "w") as f:
[Link]("Hello!")
print("Contents:", [Link]())
Python Lesson: os Module
[Link]("[Link]")
[Link]("..")
[Link]("TestFolder")
Summary Table
Function | Description
------------------------|--------------------------
[Link]() | Get current directory
[Link](path) | Change directory
[Link](path) | List directory contents
[Link](name) | Create directory
[Link](path) | Create nested directories
[Link](name) | Remove directory
[Link](file) | Delete file
[Link](old, new) | Rename file/folder
[Link](path) | Check existence
[Link](path) | Check if file
[Link](path) | Check if directory
[Link](cmd) | Run shell command