Header Ads

ad728
  • Breaking News

    Functions of OS Module



    1. File and Directory Operations:

    os.getcwd(): Get the current working directory.


    os.chdir(path): Change the current working directory to the specified path.


    os.listdir(path='.'): Return a list containing names of entries in the given directory.


    os.mkdir(path): Create a directory.


    os.makedirs(path): Create directories recursively.


    os.remove(path): Remove a file.


    os.rmdir(path): Remove a directory.


    os.removedirs(path): Remove directories recursively.


    os.rename(src, dst): Rename a file or directory.


    2. Path Manipulation:

    os.path.join(path1, path2, ...): Join one or more path components.


    os.path.abspath(path): Return the absolute version of a path.


    os.path.dirname(path): Return the directory name of a path.


    os.path.basename(path): Return the base name of a path.


    os.path.exists(path): Check if a path exists.


    os.path.isfile(path): Check if a path is a regular file.


    os.path.isdir(path): Check if a path is a directory.


    3. Environmental Variables:

    os.environ: A dictionary containing the environment variables.


    4. System Information:

    os.name: Name of the operating system dependent module imported. (e.g., 'posix', 'nt')


    os.uname(): Return information identifying the current operating system.


    5. Process Utilities:

    os.system(command): Execute the command in a subshell.


    os.spawn* and os.exec*: Low-level process creation and execution.


    6. Miscellaneous:

    os.pathsep: The character used to separate paths in the PATH variable.


    Example Usage:

    import os


    # File and Directory Operations

    print(os.getcwd())

    os.mkdir('new_directory')

    print(os.listdir())


    # Path Manipulation

    path = os.path.join('folder', 'file.txt')

    print(os.path.abspath(path))

    print(os.path.exists(path))


    # Environmental Variables

    print(os.environ['HOME'])


    # System Information

    print(os.name)

    print(os.uname())


    # Process Utilities

    os.system('ls -l')


    # Miscellaneous

    print(os.pathsep)


    1 comment: