10.1. Operating System Interface

Python provides modules that allow interaction with the underlying operating system. The primary module for this purpose is the os module, which offers a portable way to use operating system-dependent functionality.

🡆File and Directory Management:

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

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

🡆os.listdir(path): List the contents of a directory.

🡆os.mkdir(path): Create a directory.

🡆os.makedirs(path): Create directories recursively.

🡆os.rmdir(path): Remove an empty directory.

🡆os.remove(path): Remove a file.

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

Path Manipulation:

The os.path submodule provides functions for manipulating pathnames, such as

os.path.join()

os.path.exists(),

 os.path.isfile()

os.path.isdir(), etc.

Example:

import os 

def current_path():

print(“Current working directory before”)

print(os.getcwd())

print() current_path() os.chdir(‘../’) current_path()

Example

Such as interacting with a process while it’s running, the subprocess.Popen class offers more control.

import os
directory = “GeeksforGeeks”
parent_dir = “D:/Pycharm projects/”
path = os.path.join(parent_dir, directory)

os.mkdir(path)
print(“Directory ‘% s’ created” % directory)
directory = “Geeks”
parent_dir = “D:/Pycharm projects”
mode = 0o666
path = os.path.join(parent_dir, directory)
os.mkdir(path, mode)
print(“Directory ‘% s’ created” % directory)

Types of operating system Interface:

Environment Variables:
🡆os.environ: A dictionary-like object that allows access and modification of environment variables.
🡆os.system(command): Executes a command in a subshell. This method is implemented by calling the Standard C function system() and has similar limitations. 
🡆Process Management:The os module also offers functions for process management, such as os.getpid() to get the current process ID, and functions for creating and managing child processes.

While it is technically possible to build parts of an operating system in Python

It is not common practice for full-fledged operating systems due to performance considerations and the need for low-level hardware interaction typically handled by languages like C or Rust

Scroll to Top
Tutorialsjet.com