Working with directories in Python

In Python, you can work with directories (also known as folders) using the built-in `os` module. The `os` module provides many functions for interacting with the file system, including creating, deleting, and listing directories.

Here’s an example of how to create a new directory in Python:

python
import os

# Create a new directory called "my_directory"
os.mkdir("my_directory")

In this example, we first import the `os` module. We then use the `mkdir()` function to create a new directory called “my_directory” in the current working directory.

To delete a directory, you can use the `rmdir()` function:

python
import os

# Delete the directory called "my_directory"
os.rmdir("my_directory")

In this example, we use the `rmdir()` function to delete the directory called “my_directory”. Note that the directory must be empty before you can delete it using this function.

To list the contents of a directory, you can use the `listdir()` function:

python
import os

# List the contents of the current working directory
contents = os.listdir()

# Print the contents of the directory
print(contents)

In this example, we use the `listdir()` function to list the contents of the current working directory and store them in a variable called `contents`. We then print the contents of the directory.

You can also change the current working directory using the `chdir()` function:

python
import os

# Change the current working directory to "my_directory"
os.chdir("my_directory")

In this example, we use the `chdir()` function to change the current working directory to “my_directory”. Any subsequent file operations will be performed relative to this directory.