Hangman in Python (2/6): words from a file
Read a UTF-8 text file with one word per line, skip every blank line, then pick the secret hangman word at random with random.choice for each game.
Getting started
Home Assistant
Buying
Read a UTF-8 text file with one word per line, skip every blank line, then pick the secret hangman word at random with random.choice for each game.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
You already know how the mask works. To vary the games, the words come from a file: one line = one word (no spaces). You reuse the file reading from the files lesson and the hangman hub.
Quick answer — Create
mots.txt(one word per line), load it as UTF-8, drop blank lines, then userandom.choiceto draw the secret word. Sample file:/examples/mots-pendu.txt.

Example (mots.txt):
ROBOT
PYTHON
LISTE
unicodedata later.strip() and if ligne:.def charger_mots(chemin):
with open(chemin, "r", encoding="utf-8") as f:
lignes = f.read().splitlines()
mots = [L.strip().upper() for L in lignes if L.strip()]
if not mots:
raise ValueError("No words in the file.")
return mots
import random
mots = charger_mots("mots.txt")
secret = random.choice(mots)
On this site a small sample file is available as a static file: /examples/mots-pendu.txt. Locally, copy it into your working folder or adjust the path (see files and relative paths).
If the file does not exist, you get FileNotFoundError. Wrap the call in try / except (errors) and print a clear message.
random.choice.input() at startup.Why encoding="utf-8"?
So you can read accented words later. At the start, words without accents mean fewer surprises.
Relative path or absolute path?
In class, put mots.txt in the same folder as the script; see file paths.
How does this relate to the todo notebook?
Same file logic: Todo notebook part 1.
Part 3 — Show the mask, the guessed letters, and a simple hangman.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Hangman — Chapter 2/6: load words from mots_pendu.txt (UTF-8).
Run: python pendu_chapitre_02.py from this folder, or put mots_pendu.txt next to the script.
"""
import random
from pathlib import Path
BASE = Path(__file__).resolve().parent
CHEMIN_MOTS = BASE / "mots_pendu.txt"
def charger_mots(chemin):
with open(chemin, "r", encoding="utf-8") as f:
lignes = f.read().splitlines()
mots = [L.strip().upper() for L in lignes if L.strip()]
if not mots:
raise ValueError("No words in the file.")
return mots
def main():
try:
mots = charger_mots(CHEMIN_MOTS)
except FileNotFoundError:
print("File not found:", CHEMIN_MOTS)
print("Copy mots_pendu.txt into the same folder as this script.")
return
secret = random.choice(mots)
print(len(mots), "words loaded. (A real game does not show the secret.)")
print("Length of the drawn word:", len(secret))
if __name__ == "__main__":
main()
pendu_chapitre_02.py — also download mots_pendu.txt and put both in the same local folder.
A book search for Python, data and files: Amazon.co.uk.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).