Lire un fichier
Python peut lire et écrire des fichiers sur votre ordinateur. La fonction open() ouvre un fichier :
# Lire tout le contenu d'un fichier
with open("mon_fichier.txt", "r") as f:
contenu = f.read()
print(contenu)
# Lire ligne par ligne
with open("mon_fichier.txt", "r") as f:
for ligne in f:
print(ligne.strip()) # strip() enlève le \n
Le mot-clé with ferme automatiquement le fichier à la fin du bloc. C'est la manière recommandée en Python.
Modes d'ouverture : "r" = lecture, "w" = écriture (écrase), "a" = ajout, "r+" = lecture + écriture.
Écrire dans un fichier
# Écrire (écrase le contenu existant)
with open("resultats.txt", "w") as f:
f.write("Score : 95/100\n")
f.write("Statut : Réussi\n")
# Ajouter à la fin (sans écraser)
with open("log.txt", "a") as f:
f.write("2026-05-27 : Connexion réussie\n")
Résultat dans resultats.txt :
Score : 95/100
Statut : Réussi
import — les modules
Un module est un fichier Python contenant des fonctions réutilisables. Python en fournit des centaines :
# Importer un module entier
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# Importer une fonction spécifique
from random import randint
print(randint(1, 10)) # nombre aléatoire entre 1 et 10
# Renommer un import (alias)
import datetime as dt
maintenant = dt.datetime.now()
print(maintenant) # 2026-05-27 14:30:00.123456
pip install — les packages externes
La bibliothèque standard de Python est riche, mais pour des besoins spécifiques, on installe des packages externes avec pip :
# Dans le terminal (pas dans Python)
pip install requests # requêtes HTTP
pip install beautifulsoup4 # web scraping
pip install pandas # data science
pip install flask # framework web
Une fois installé, on l'importe normalement :
import requests
response = requests.get("https://api.example.com/data")
print(response.status_code) # 200
Bonne pratique : utilisez un environnement virtuel (python -m venv mon_env) pour isoler les packages de chaque projet.
Modules utiles : os, json, datetime
# os — manipuler le système de fichiers
import os
print(os.getcwd()) # dossier courant
print(os.listdir(".")) # lister les fichiers
os.makedirs("data", exist_ok=True) # créer un dossier
# json — lire/écrire du JSON
import json
# Écrire du JSON
data = {"nom": "Alice", "scores": [95, 87, 92]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Lire du JSON
with open("data.json", "r") as f:
data = json.load(f)
print(data["nom"]) # Alice
# datetime — dates et heures
from datetime import datetime, timedelta
maintenant = datetime.now()
demain = maintenant + timedelta(days=1)
print(maintenant.strftime("%d/%m/%Y %H:%M")) # 27/05/2026 14:30
Créer son propre module
N'importe quel fichier .py est un module. Créez outils.py :
# outils.py
def formater_prix(montant, devise="€"):
return f"{montant:.2f} {devise}"
def calculer_tva(prix_ht, taux=20):
return prix_ht * (1 + taux / 100)
Puis importez-le dans un autre fichier :
# main.py
from outils import formater_prix, calculer_tva
prix_ttc = calculer_tva(100)
print(formater_prix(prix_ttc)) # 120.00 €
Reading a file
Python can read and write files on your computer. The open() function opens a file:
# Read the entire content of a file
with open("my_file.txt", "r") as f:
content = f.read()
print(content)
# Read line by line
with open("my_file.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes \n
The with keyword automatically closes the file at the end of the block. This is the recommended way in Python.
Opening modes: "r" = read, "w" = write (overwrites), "a" = append, "r+" = read + write.
Writing to a file
# Write (overwrites existing content)
with open("results.txt", "w") as f:
f.write("Score: 95/100\n")
f.write("Status: Passed\n")
# Append to the end (without overwriting)
with open("log.txt", "a") as f:
f.write("2026-05-27: Login successful\n")
Result in results.txt:
Score: 95/100
Status: Passed
import — modules
A module is a Python file containing reusable functions. Python provides hundreds of them:
# Import an entire module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# Import a specific function
from random import randint
print(randint(1, 10)) # random number between 1 and 10
# Rename an import (alias)
import datetime as dt
now = dt.datetime.now()
print(now) # 2026-05-27 14:30:00.123456
pip install — external packages
Python's standard library is rich, but for specific needs, install external packages with pip:
# In the terminal (not in Python)
pip install requests # HTTP requests
pip install beautifulsoup4 # web scraping
pip install pandas # data science
pip install flask # web framework
Once installed, import it normally:
import requests
response = requests.get("https://api.example.com/data")
print(response.status_code) # 200
Best practice: use a virtual environment (python -m venv my_env) to isolate each project's packages.
Useful modules: os, json, datetime
# os — manipulate the file system
import os
print(os.getcwd()) # current directory
print(os.listdir(".")) # list files
os.makedirs("data", exist_ok=True) # create a folder
# json — read/write JSON
import json
# Write JSON
data = {"name": "Alice", "scores": [95, 87, 92]}
with open("data.json", "w") as f:
json.dump(data, f, indent=2)
# Read JSON
with open("data.json", "r") as f:
data = json.load(f)
print(data["name"]) # Alice
# datetime — dates and times
from datetime import datetime, timedelta
now = datetime.now()
tomorrow = now + timedelta(days=1)
print(now.strftime("%d/%m/%Y %H:%M")) # 27/05/2026 14:30
Creating your own module
Any .py file is a module. Create utils.py:
# utils.py
def format_price(amount, currency="EUR"):
return f"{amount:.2f} {currency}"
def calculate_vat(price_excl, rate=20):
return price_excl * (1 + rate / 100)
Then import it in another file:
# main.py
from utils import format_price, calculate_vat
price_incl = calculate_vat(100)
print(format_price(price_incl)) # 120.00 EUR
Copiez ce prompt dans Claude ou ChatGPT :
Écris un script Python qui lit un fichier CSV de contacts, le convertit en JSON, et crée un résumé avec le nombre de contacts par ville. Utilise les modules csv, json et collections.
with open() plutôt que open() seul ?