Python
ImportError
YAML
ModuleNotFoundError
Troubleshooting

ModuleNotFoundError: No module named 'yaml' in Python

Codemia Knowledge Hub ·

Python cannot find the YAML library in the interpreter you are running. Install the PyYAML package into that same interpreter with python -m pip install pyyaml. If it is already installed, either a different interpreter is running your script or a local file named yaml.py is shadowing the real module.

The package name is the first trap: you write import yaml, but the package on PyPI is PyYAML, not yaml.

Install PyYAML into the right interpreter

Use python -m pip rather than bare pip, so the package lands in the interpreter that will run your script:

bash
python -m pip install pyyaml

Where python3 is the correct binary (common on macOS and many Linux distributions):

bash
python3 -m pip install pyyaml

Then verify:

bash
python -m pip show pyyaml
python -c "import yaml; print(yaml.__version__)"

pip show confirms the package is installed, and the import test confirms the interpreter can load it.

Why you install pyyaml but import yaml

Many packages use a different name on PyPI than the module you import. PyYAML installs a module named yaml. Similar cases:

PyPI Package NameImport Name
PyYAMLyaml
PillowPIL
scikit-learnsklearn
python-dateutildateutil
beautifulsoup4bs4

pip install yaml either fails or installs a different, largely abandoned package. Always install pyyaml.

Fixing virtual environment mismatches

The most frequent cause is installing PyYAML into one environment and running the script in another: a virtual environment, a Conda environment, or a system versus user install.

Create and activate a virtual environment

bash
1python -m venv .venv
2source .venv/bin/activate      # macOS/Linux
3# .venv\Scripts\Activate.ps1   # Windows PowerShell
4python -m pip install pyyaml
5python -c "import yaml; print('ok')"

See which interpreter is active

bash
which python          # macOS/Linux
where python          # Windows
python -c "import sys; print(sys.executable)"

If sys.executable does not point to the environment where you installed pyyaml, that is the problem. Activate the right environment or install into the one you are using. Forgetting to activate the venv in the current shell has the same effect: the package is inside the venv, but the script runs with the system Python.

Check the IDE interpreter

VS Code, PyCharm and other IDEs keep their own interpreter setting, separate from your terminal. If the IDE uses the system Python while your terminal uses a virtual environment (or the reverse), the import fails in one place and works in the other. Point the IDE's interpreter selector at the same environment.

Fixing a local file that shadows yaml

A file named yaml.py or a directory named yaml/ in your project can be imported instead of the real package:

text
project/
  yaml.py        <-- this shadows the real package
  app.py

The current directory comes first on sys.path, so import yaml in app.py finds the local file. Rename it and delete the cached bytecode, because Python may otherwise keep loading the old __pycache__/yaml.cpython-*.pyc:

bash
mv yaml.py yaml_config.py
rm -rf __pycache__

To see which file Python actually loaded:

python
import yaml
print(yaml.__file__)

If the path points into your project instead of site-packages, shadowing is the cause.

Using PyYAML once it imports

A minimal round trip that parses and dumps YAML:

python
1import yaml
2
3# Parse YAML from a string
4text = """
5database:
6  host: localhost
7  port: 5432
8  credentials:
9    user: admin
10    password: secret
11"""
12
13config = yaml.safe_load(text)
14print(config["database"]["host"])   # localhost
15print(config["database"]["port"])   # 5432
16
17# Dump a Python dict back to YAML
18output = yaml.dump(config, default_flow_style=False)
19print(output)

Use safe_load and safe_dump by default. Calling yaml.load() without a Loader argument is deprecated and unsafe, because it can construct arbitrary Python objects embedded in the YAML.

Loading a configuration file from disk:

python
1import yaml
2from pathlib import Path
3
4config_path = Path("config.yml")
5
6with config_path.open() as f:
7    config = yaml.safe_load(f)
8
9print(config)

Writing it back:

python
with config_path.open("w") as f:
    yaml.dump(config, f, default_flow_style=False, sort_keys=False)

sort_keys=False keeps the original key order, which is usually what you want for configuration files.

ImportError vs ModuleNotFoundError

Since Python 3.6 you may see ModuleNotFoundError instead of ImportError. It is a subclass of ImportError, so except ImportError still catches it, and the fixes are the same.

python
1try:
2    import yaml
3except ImportError:
4    print("PyYAML is not installed. Run: python -m pip install pyyaml")
5    raise

Docker and CI environments

In containers and CI, the error usually means pyyaml is missing from requirements.txt or the install step did not run.

dockerfile
1FROM python:3.12-slim
2WORKDIR /app
3COPY requirements.txt .
4RUN pip install --no-cache-dir -r requirements.txt
5COPY . .
6CMD ["python", "app.py"]

Make sure pyyaml is listed in requirements.txt:

text
pyyaml>=6.0

In CI pipelines, the install step must run before any script that imports yaml.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms