> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/python/library/os.md).

# os

The `os` module in Python provides a wide range of functions to interact with the operating system.&#x20;

***

### **1. File and Directory Management**

#### **`os.getcwd()`**

* **Purpose**: Get the current working directory.

```python
import os
print(os.getcwd())
```

#### **`os.chdir(path)`**

* **Purpose**: Change the current working directory.

```python
os.chdir('/tmp')
print(os.getcwd())
```

#### **`os.listdir(path)`**

* **Purpose**: List all files and directories in the given path.

```python
print(os.listdir('.'))
```

#### **`os.mkdir(path)`**

* **Purpose**: Create a single directory.

```python
os.mkdir('example_dir')
```

#### **`os.makedirs(path)`**

* **Purpose**: Create directories recursively.

```python
os.makedirs('parent_dir/child_dir')
```

#### **`os.rmdir(path)`**

* **Purpose**: Remove an empty directory.

```python
os.rmdir('example_dir')
```

#### **`os.removedirs(path)`**

* **Purpose**: Remove directories recursively.

```python
os.removedirs('parent_dir/child_dir')
```

#### **`os.rename(src, dst)`**

* **Purpose**: Rename a file or directory.

```python
os.rename('old_name.txt', 'new_name.txt')
```

#### **`os.remove(path)`**

* **Purpose**: Remove a file.

```python
os.remove('example_file.txt')
```

***

### **2. Working with Files**

#### **`os.path` Module**

The `os.path` submodule provides functions for working with file paths.

**Examples:**

```python
# Check if a path exists
print(os.path.exists('example_file.txt'))

# Check if a path is a file
print(os.path.isfile('example_file.txt'))

# Check if a path is a directory
print(os.path.isdir('example_dir'))

# Get the absolute path
print(os.path.abspath('example_file.txt'))

# Split a file into directory and base name
print(os.path.split('/path/to/example_file.txt'))  # Output: ('/path/to', 'example_file.txt')

# Get the file's extension
print(os.path.splitext('example_file.txt'))  # Output: ('example_file', '.txt')

# Get the current file basenaem
print(os.path.basename(__file__))

```

***

### **3. Environment Variables**

#### **`os.getenv(key, default=None)`**

* **Purpose**: Get the value of an environment variable.

```python
print(os.getenv('HOME'))
```

#### **`os.putenv(key, value)`**

* **Purpose**: Set an environment variable (deprecated in favor of `os.environ`).

```python
os.putenv('MY_ENV_VAR', 'value')
```

#### **`os.environ`**

* **Purpose**: Access or modify environment variables as a dictionary.

```python
# Get an environment variable
print(os.environ.get('HOME'))

# Set an environment variable
os.environ['MY_ENV_VAR'] = 'value'
```

***

### **4. Process Management**

#### **`os.system(command)`**

* **Purpose**: Run a shell command (returns the command's exit status).

```python
os.system('echo Hello, World!')
```

#### **`os.popen(command)`**

* **Purpose**: Open a pipe to or from a command (deprecated in favor of `subprocess`).

```python
with os.popen('ls') as pipe:
    print(pipe.read())
```

#### **`os.getpid()`**

* **Purpose**: Get the current process ID.

```python
print(os.getpid())
```

#### **`os.getppid()`**

* **Purpose**: Get the parent process ID.

```python
print(os.getppid())
```

***

### **5. Permissions and Ownership**

#### **`os.chmod(path, mode)`**

* **Purpose**: Change the permissions of a file or directory.

```python
import stat
os.chmod('example_file.txt', stat.S_IRWXU)  # Full permissions for the owner
```

#### **`os.chown(path, uid, gid)`**

* **Purpose**: Change the owner and group of a file.

```python
os.chown('example_file.txt', 1000, 1000)
```

***

### **6. System Information**

#### **`os.uname()`**

* **Purpose**: Get system information (only available on Unix-like systems).

```python
print(os.uname())
```

#### **`os.name`**

* **Purpose**: Get the name of the operating system-dependent module imported (`posix`, `nt`).

```python
print(os.name)
```

#### **`os.cpu_count()`**

* **Purpose**: Get the number of CPUs in the system.

```python
print(os.cpu_count())
```

#### **`os.getloadavg()`**

* **Purpose**: Get system load averages (Unix-like systems only).

```python
print(os.getloadavg())
```

***

### **7. Miscellaneous**

#### **`os.urandom(n)`**

* **Purpose**: Generate `n` random bytes suitable for cryptographic use.

```python
print(os.urandom(16))
```

#### **`os.walk(top)`**

* **Purpose**: Generate file names in a directory tree by walking the tree.

```python
for dirpath, dirnames, filenames in os.walk('.'):
    print('Directory:', dirpath)
    print('Subdirectories:', dirnames)
    print('Files:', filenames)
```

***

### **Commonly Used Constants**

* `os.sep`: The directory separator (e.g., `/` on Unix, `\` on Windows).
* `os.linesep`: The line separator (e.g., `\n` on Unix, `\r\n` on Windows).
* `os.pathsep`: The separator used in environment variables like `PATH`.
* `os.devnull`: The path to the null device (e.g., `/dev/null` on Unix).

```python
print("Directory Separator:", os.sep)
print("Line Separator:", repr(os.linesep))
print("Path Separator:", os.pathsep)
print("Null Device:", os.devnull
```
