To use functions from the os module, you first need to import it:
import os
Get Current Working Directory:
current_directory = os.getcwd()
# Returns a string representing the current directory path.
Change Directory:
os.chdir("path/to/new/directory")
# Changes the current working directory to the specified path.
"path/to/new/directory": A string representing the target directory path.List Directory Contents:
items_in_directory = os.listdir("path/to/directory")
# Returns a list of names (files and subdirectories) in the specified path.
"path/to/directory": The path to list. If omitted, lists the current directory (.).Create Directory:
os.mkdir("new_directory_name")
# Creates a new directory. Raises FileExistsError if it already exists.
"new_directory_name": The name or path of the directory to create.Create Directories (including parents):
os.makedirs("path/to/new/nested/directories")
# Creates directories recursively. Creates parent directories if they don't exist.
"path/to/new/nested/directories": The path to create.Join Path Components:
full_path = os.path.join("directory", "subdirectory", "filename.txt")
# Joins path components intelligently, handling separators ('/' or '\\') correctly for the OS.
Check if Path Exists:
exists = os.path.exists("path/to/file_or_directory")
# Returns True if the path exists, False otherwise.
"path/to/file_or_directory": The path to check.Check if Path is a File:
is_file = os.path.isfile("path/to/file.txt")
# Returns True if the path is an existing file, False otherwise.
Check if Path is a Directory:
is_dir = os.path.isdir("path/to/directory")
# Returns True if the path is an existing directory, False otherwise.
Get Absolute Path:
abs_path = os.path.abspath("relative/path")
# Returns the absolute path of a file or directory.
Get Directory Name from Path:
dir_name = os.path.dirname("path/to/file.txt")
# Returns the directory portion of a path.
Get Base Name from Path:
base_name = os.path.basename("path/to/file.txt")
# Returns the file or directory name portion of a path.