The OS Module in Python provides a way of interacting with the operating system. It gives many useful OS functions that are used to perform Operating system based tasks and get related information about the operating system.
It offers a wide range of functions for performing tasks such as file and directory operations, process management, environment variables, and more.
The OS Module comes with Python's standard pre-installed modules. we don't need to install it manually.
Common functionalities provided by the "os" module:
Returns the current working directory.
# import os module import os print(os.getcwd())
Changes the current working directory to the specified path.
# import os module import os os.chdir("/path/to/new/directory")
Returns a list of all files and directories in the specified directory.
# import os module import os print(os.listdir("/path/to/directory"))
Creates a new directory.
# import os module import os os.mkdir("/path/to/new/directory")
Removes the specified directory.
# import os module import os os.rmdir("/path/to/directory")
Removes the specified file.
# import os module import os os.remove("/path/to/file.txt")
Checks whether a file or directory exists.
# import os module import os if os.path.exists("/path/to/file.txt"): print("File exists")
A mapping object representing the environment variables.
# import os module import os print(os.environ['HOME'])
Executes the command in a subshell.
# import os module import os os.system("ls -l")
Concatenates path components.
# import os module import os filepath = os.path.join("/path/to", "directory", "sample.txt")
Returns the base name of the specified path.
# import os module import os print(os.path.basename("/path/to/sample.txt"))
Returns the directory name of the specified path.
# import os module import os print(os.path.dirname("/path/to/sample.txt"))
In Python, `os.name` is an attribute of the os module that provides the name of the operating-system dependent module imported. The value of `os.name` depends on the underlying operating system Python runs. It can have different values such as 'POSIX', 'nt', 'java', etc., representing different operating systems.
# import os module import os print(os.name) # Output depends on the operating system
os.error() raised by the os level error. This exception is a subclass of the built-in OSError exception and it is raised when it encounters any issue in the accessibility or invalid file path provided.
import os try: # Try to remove a file that doesn't exist os.remove("sample_not_exist_file.txt") except os.error as e: print(f"Error: {e}")
It provides many more functions for various operating system-related tasks.
Always ensure to import the "os" module (import os) before using its functions.