# Python OS Module

The `os` module provides a portable way of using operating system dependent functionality. It allows you to interact with the underlying operating system, including file system operations, environment variables, and process management.

## Importing the Module

```python
import os
```

## File and Directory Operations

### Getting Current Working Directory

```python
cwd = os.getcwd()
print(cwd)
```

### Changing Directory

```python
os.chdir('/path/to/directory')
```

### Listing Files

```python
files = os.listdir('.')
print(files)
```

### Creating Directories

```python
# Create a single directory
os.mkdir('new_folder')

# Create directory tree (nested directories)
os.makedirs('parent/child/grandchild')
```

### Removing Files and Directories

```python
# Remove a file
os.remove('file.txt')

# Remove an empty directory
os.rmdir('empty_folder')
```

## Path Manipulation (`os.path`)

The `os.path` submodule provides useful functions on pathnames.

```python
path = '/home/user/docs/file.txt'

# Get the directory name
print(os.path.dirname(path)) # /home/user/docs

# Get the base name (filename)
print(os.path.basename(path)) # file.txt

# Check if path exists
print(os.path.exists(path))

# Join paths intelligently
new_path = os.path.join('/home/user', 'downloads', 'image.png')
```

## Environment Variables

You can access environment variables using `os.environ`.

```python
# Get an environment variable
user = os.environ.get('USER')

# Set an environment variable (for the current process)
os.environ['MY_VAR'] = 'some_value'
```

## Running System Commands

While `subprocess` is generally preferred, `os.system()` is a simple way to run a command.

```python
os.system('echo "Hello World"')
```

[[programming/python/python]]