Python OS Module With Examples

PYTHON OS MODULE: 

The 'os' module in Python provides a way to interact with the operating system, allowing you to perform various tasks such as file and directory operations, process management, environment variables, and more. It abstracts many low-level operating system functionalities into Python functions, making it easier to write platform-independent code that interacts with the underlying system.


reload ! diplomawaale.blogspot.com
OS Module In Python


DIFFERENT TYPE OF FUNCTION IN OS MODULE:

File and Directory Operations:

    • os.listdir(path): Returns a list of filenames in the given directory.
    • os.mkdir(path): Creates a directory with the specified path.
    • os.makedirs(path): Creates a directory with all necessary intermediate directories.
    • os.remove(path): Deletes a file at the given path.
    • os.rmdir(path): Removes an empty directory.
    • os.rename(old, new): Renames a file or directory.
    • os. path submodule: Contains functions for working with file paths, like os. path.join(), os.path.exists(), os.path.abspath(), etc.

Process and System Information:

    • os.system(command): Executes a shell command.
    • os.environ: Provides access to the environment variables.
    • os.getpid(): Returns the process ID of the current process.
    • os.getcwd(): Returns the current working directory.
    • os.chdir(path): Changes the current working directory.

Platform-Dependent Functionality:

    • os.name: Returns the name of the operating system (e.g., 'posix', 'nt', 'mac', etc.).
    • os.sep: Returns the platform-specific path separator ('/' on Unix-like systems, '\' on Windows).

File and Directory Information:

    • os.stat(path): Returns file or directory statistics.
    • os.path.getsize(path): Returns the size of a file in bytes.
    • os.path.getmtime(path): Returns the last modification time of a file.

Path Manipulation and Navigation:

    • os.path.join(path, *paths): Joins path components using the appropriate separator.
    • os.path.dirname(path): Returns the directory component of a path.
    • os.path.basename(path): Returns the base name (filename) of a path.

File Permissions:

    • os.chmod(path, mode): Changes the permissions of a file.
    • os. access(path, mode): Checks if a file or directory is accessible with the specified mode.

EXAMPLE:

                                import os

                                # Create a directory
                                new_directory = "new_dir"
                                os.mkdir(new_directory)
                                print(f"Created directory: {new_directory}")

                                # List files in the current directory
                                files_in_dir = os.listdir(".")
                                print(f"Files in current directory: {files_in_dir}")

                                # Create a file in the new directory
                                new_file_path = os.path.join(new_directory, "new_file.txt")
                                with open(new_file_path, "w") as f:
                               f.write("Hello, this is a new file!")

                              # Get the size of the new file
                              file_size = os.path.getsize(new_file_path)
                              print(f"Size of {new_file_path}: {file_size} bytes")

                              # Rename the file
                              new_file_path_renamed = os.path.join(new_directory, "renamed_file.txt")
                              os.rename(new_file_path, new_file_path_renamed)

                             # Display the current working directory
                             current_dir = os.getcwd()
                             print(f"Current working directory: {current_dir}")

                             # Display environment variable
                             home_directory = os.environ.get("HOME")
                             print(f"Home directory: {home_directory}")

                            # Execute a system command
                            os.system("ls -l")

                            # Remove the renamed file
                            os.remove(new_file_path_renamed)

                             # Remove the directory
                             os.rmdir(new_directory)
                             print(f"Removed directory: {new_directory}")

ADVANTAGE OF PYTHON OS MODULE:

  1. Cross-Platform Compatibility: The OS module abstracts many low-level operating system functionalities, providing a consistent interface across different platforms (such as Windows, macOS, and various Unix-like systems). This allows you to write code that works on multiple operating systems without having to worry about platform-specific details.


    File and Directory Operations: The module provides a wide range of functions for file and directory manipulation, such as creating, renaming, deleting, and navigating directories. This makes it convenient to work with files and directories from within your Python code.


    Process Management: You can use the os module to manage processes, execute shell commands, and interact with system-level processes. This is useful for automating tasks, running external programs, and managing subprocesses.


    Environment Variables: You can access and modify environment variables using the os. environ dictionary-like object. This helps access system configuration settings and pass data between processes.


    Path Manipulation: The os. path submodule provides functions for working with file paths in a platform-independent manner. This helps you avoid issues related to path separators and differences between operating systems.


    Access to System Information: The OS module allows you to gather information about the system, such as the current working directory, the user's home directory, the operating system's name, and process-related information like process IDs.


    Permission Control: You can use the os module to change file permissions and perform access checks to determine if you have read, write, or execute permissions on a file or directory.


    System Calls and Shell Commands: The OS module enables you to make system calls and execute shell commands from within your Python code. This can be useful for interacting with system utilities and tools.


    Error Handling: The OS module provides functions that raise exceptions when errors occur, allowing you to handle exceptions gracefully in your code and take appropriate actions.


    Customization: You can customize the behavior of your Python scripts based on the underlying operating system's characteristics using the information provided by the OS module.

Post a Comment

0 Comments