The os Module in Python
The os module provides functions to interact with the operating system’s file system.
We can navigate directories, create or remove folders, and rename or delete files using this module.
Below are common tasks and how to perform them with os:
Step 1: Get Current Working Directory
Use os.getcwd() to find out the current working directory (CWD) of your script.
Steps:
-
Open Visual Studio Code.
-
Open folder Beginner Python with Automation.
-
Activate Virtual Environment.
-
In a new file lesson5.py, enter:
import os
cwd = os.getcwd()
print("Current working directory:", cwd)
Result:
When you run this file, it will output the path of the directory your program is currently running in.
Step 2: Change Current Working Directory
Use os.chdir(path) to change the current working directory.
-
os.chdir('..')moves one level up from the current directory. -
Always ensure the target path exists, or Python will raise an error.
Step 3: List Directory Contents
Use os.listdir(path) to get a list of files and subfolders in the given directory.
If no path is provided, it lists the contents of the current directory.
files = os.listdir('.') # list files in current directory
for name in files:
print(name)
Note: You can also use os.scandir() or os.walk() for more advanced listing, but os.listdir() is straightforward for simple needs.
Step 4: Create Directories
Use os.mkdir(path) to create a new directory at the specified path.
If intermediate folders don’t exist, use os.makedirs(path) to create all necessary directories recursively.
os.mkdir('example_folder')
# or create nested dirs in one go
os.makedirs('parent_folder/child_folder', exist_ok=True)
Tip:exist_ok=True in os.makedirs will not raise an error if the directory already exists.
Step 5: Rename Files or Folders
Use os.rename(old_name, new_name) to rename a file or directory.
os.rename('old_name.txt', 'new_name.txt')
-
The old name must exactly match an existing file/folder.
-
You can also move files by specifying a new full path.
-
If the file doesn’t exist, a
FileNotFoundErroris raised.
Step 6: Delete Files
Use os.remove(file_path) to delete a file.
os.remove('unneeded_file.txt')
Be careful – this is permanent.
If the file does not exist, Python will throw a FileNotFoundError.
Step 7: Delete Directories
Use os.rmdir(dir_path) to remove an empty directory.
os.rmdir('empty_folder')
-
If the directory is not empty,
os.rmdirwill error. -
To remove a directory and all its contents, you must first delete all files inside (possibly using a loop or the
shutilmodule). -
You can also use
shutil.rmtree()to remove an entire directory tree (use with caution).
