Files
Manage input and output effectively in your programs
File Handling in Python
File handling is a fundamental programming skill, essential for saving data, processing information, and automating tasks. Python offers powerful and flexible tools for working with different types of files. In this tutorial, we will explore how to read, write, and manipulate files in Python.
File Handling Basics
Opening and Closing Files
In Python, you use the open() function to open a file, which returns a file object:
# Ouvrir un fichier en mode lecture
fichier = open("mon_fichier.txt", "r")
# Opérations sur le fichier
# ...
# Fermer le fichier
fichier.close()
The open() function takes two main parameters:
- The file path (can be absolute or relative)
- The mode (read, write, etc.)
File Modes
Python offers several modes for opening files:
'r': Read (default mode)'w': Write (creates a new file or overwrites an existing file)'a': Append (adds content to the end of an existing file)'b': Binary mode (e.g.,'rb'to read in binary)'t': Text mode (default, e.g.,'rt'to read text)'+': Update mode (read and write, e.g.,'r+')
Using the with Block
The best practice for working with files is to use the with block, which automatically closes the file, even if an error occurs:
# Meilleure façon d'ouvrir un fichier
with open("mon_fichier.txt", "r") as fichier:
# Opérations sur le fichier
contenu = fichier.read()
print(contenu)
# Le fichier est automatiquement fermé à la sortie du bloc with
Reading Files
Python offers several methods for reading the contents of a file.
Reading the Entire File
with open("mon_fichier.txt", "r") as fichier:
contenu = fichier.read()
print(contenu)
Reading Line by Line
with open("mon_fichier.txt", "r") as fichier:
# Lire la première ligne
premiere_ligne = fichier.readline()
print(premiere_ligne)
# Lire la deuxième ligne
deuxieme_ligne = fichier.readline()
print(deuxieme_ligne)
Reading All Lines into a List
with open("mon_fichier.txt", "r") as fichier:
lignes = fichier.readlines()
for ligne in lignes:
print(ligne.strip()) # strip() supprime les espaces et les sauts de ligne
Iterating Over a File Line by Line (Efficient Method for Large Files)
with open("mon_fichier.txt", "r") as fichier:
for ligne in fichier:
print(ligne.strip())
This last method is particularly efficient for large files because it loads only one line into memory at a time.
Writing to Files
Writing Text
with open("mon_fichier.txt", "w") as fichier:
fichier.write("Bonjour, voici une ligne de texte.\n")
fichier.write("Et voici une deuxième ligne.")
The write() method does not automatically add a newline at the end of the text, so you must add one explicitly with \n when needed.
Appending Text to an Existing File
with open("mon_fichier.txt", "a") as fichier:
fichier.write("\nCette ligne est ajoutée à la fin du fichier.")
Writing Multiple Lines at Once
lignes = ["Ligne 1", "Ligne 2", "Ligne 3"]
with open("mon_fichier.txt", "w") as fichier:
fichier.writelines(ligne + "\n" for ligne in lignes)
Managing File Paths
The os.path module provides functions for working with file paths in a way that is compatible with different operating systems:
import os.path
# Vérifier si un fichier existe
if os.path.exists("mon_fichier.txt"):
print("Le fichier existe.")
# Vérifier si c'est un fichier ou un répertoire
if os.path.isfile("mon_fichier.txt"):
print("C'est un fichier.")
if os.path.isdir("mon_dossier"):
print("C'est un répertoire.")
# Obtenir le chemin absolu
chemin_absolu = os.path.abspath("mon_fichier.txt")
print(chemin_absolu)
# Joindre des parties de chemins
chemin_complet = os.path.join("dossier", "sous_dossier", "fichier.txt")
print(chemin_complet)
For more advanced file path operations, the pathlib module (available since Python 3.4) offers a more modern, object-oriented interface:
from pathlib import Path
# Créer un objet Path
chemin = Path("dossier/sous_dossier/fichier.txt")
# Vérifier si le fichier existe
if chemin.exists():
print("Le fichier existe.")
# Obtenir le répertoire parent
parent = chemin.parent
print(parent)
# Créer un nouveau chemin en joignant
nouveau_chemin = parent / "autre_fichier.txt"
print(nouveau_chemin)
Working with CSV Files
CSV (Comma-Separated Values) files are commonly used to store tabular data. Python provides the csv module to work with these files easily.
Reading a CSV File
import csv
with open("donnees.csv", "r", newline="") as fichier_csv:
lecteur = csv.reader(fichier_csv)
# Lire l'en-tête
en_tete = next(lecteur)
print(f"Colonnes : {en_tete}")
# Lire les données
for ligne in lecteur:
print(ligne)
Reading a CSV File into Dictionaries
import csv
with open("donnees.csv", "r", newline="") as fichier_csv:
lecteur = csv.DictReader(fichier_csv)
for ligne in lecteur:
print(f"Nom: {ligne['nom']}, Âge: {ligne['age']}")
Writing to a CSV File
import csv
donnees = [
["Nom", "Âge", "Ville"],
["Alice", "30", "Paris"],
["Bob", "25", "Lyon"],
["Charlie", "35", "Marseille"]
]
with open("personnes.csv", "w", newline="") as fichier_csv:
ecrivain = csv.writer(fichier_csv)
ecrivain.writerows(donnees)
Writing to a CSV File Using Dictionaries
import csv
donnees = [
{"nom": "Alice", "age": 30, "ville": "Paris"},
{"nom": "Bob", "age": 25, "ville": "Lyon"},
{"nom": "Charlie", "age": 35, "ville": "Marseille"}
]
with open("personnes.csv", "w", newline="") as fichier_csv:
champs = ["nom", "age", "ville"]
ecrivain = csv.DictWriter(fichier_csv, fieldnames=champs)
ecrivain.writeheader()
ecrivain.writerows(donnees)
Working with JSON Files
JSON (JavaScript Object Notation) is a lightweight data interchange format. Python provides the json module to work with this format.
Reading a JSON File
import json
with open("donnees.json", "r") as fichier_json:
donnees = json.load(fichier_json)
print(donnees)
Writing to a JSON File
import json
donnees = {
"personnes": [
{"nom": "Alice", "age": 30, "ville": "Paris"},
{"nom": "Bob", "age": 25, "ville": "Lyon"},
{"nom": "Charlie", "age": 35, "ville": "Marseille"}
]
}
with open("personnes.json", "w") as fichier_json:
json.dump(donnees, fichier_json, indent=4) # indent pour un format plus lisible
Handling Binary Files
Binary files contain data that is not in a human-readable text format. Python can handle them using the 'b' mode.
Reading a Binary File
with open("image.jpg", "rb") as fichier_binaire:
donnees = fichier_binaire.read()
print(f"Taille du fichier : {len(donnees)} octets")
Writing to a Binary File
donnees_binaires = b'\x00\x01\x02\x03' # Exemple de données binaires
with open("binaire.bin", "wb") as fichier_binaire:
fichier_binaire.write(donnees_binaires)
Exception Handling in File Operations
When working with files, it is important to handle the exceptions that may occur:
try:
with open("fichier_inexistant.txt", "r") as fichier:
contenu = fichier.read()
except FileNotFoundError:
print("Le fichier n'existe pas.")
except PermissionError:
print("Vous n'avez pas les permissions nécessaires pour accéder à ce fichier.")
except IsADirectoryError:
print("C'est un répertoire, pas un fichier.")
except Exception as e:
print(f"Une erreur inattendue s'est produite : {e}")
Working with Folders (Directories)
Python provides functions for creating, listing, and deleting directories.
Creating a Directory
import os
# Créer un seul répertoire
os.mkdir("nouveau_dossier")
# Créer des répertoires imbriqués
os.makedirs("parent/enfant/petit-enfant", exist_ok=True) # exist_ok=True évite l'erreur si le dossier existe déjà
Listing the Contents of a Directory
import os
# Lister tous les fichiers et dossiers
contenu = os.listdir("mon_dossier")
print(contenu)
# Obtenir uniquement les fichiers
fichiers = [f for f in os.listdir("mon_dossier") if os.path.isfile(os.path.join("mon_dossier", f))]
print(fichiers)
Walking a Directory Tree
import os
for dossier_racine, sous_dossiers, fichiers in os.walk("mon_dossier"):
print(f"Dossier actuel : {dossier_racine}")
print(f"Sous-dossiers : {sous_dossiers}")
print(f"Fichiers : {fichiers}")
print()
Using Temporary Files
The tempfile module lets you create temporary files and directories:
import tempfile
# Créer un fichier temporaire
with tempfile.TemporaryFile() as tmp:
tmp.write(b"Données temporaires")
tmp.seek(0) # Retourner au début du fichier
data = tmp.read()
print(data)
# Le fichier est automatiquement supprimé
# Créer un répertoire temporaire
with tempfile.TemporaryDirectory() as tmp_dir:
print(f"Répertoire temporaire créé : {tmp_dir}")
# Le répertoire est automatiquement supprimé
Understanding Character Encodings
When working with text files, character encoding is important, especially for text containing non-ASCII characters.
# Spécifier l'encodage lors de l'ouverture du fichier
with open("fichier_utf8.txt", "r", encoding="utf-8") as f:
texte = f.read()
# Écrire avec un encodage spécifique
with open("nouveau_fichier.txt", "w", encoding="utf-8") as f:
f.write("Texte avec des caractères spéciaux : éèêà")
Common encodings include:
'utf-8': The most common encoding for the web and modern systems'latin-1'or'iso-8859-1': An older encoding for Western European languages'ascii': Limited to ASCII characters (0-127)'cp1252': The default Windows encoding for Western European languages
Best Practices
- Always use
withto manage files, ensuring they are closed even if an error occurs. - Specify the encoding when opening text files to avoid problems with special characters.
- Handle file-related exceptions to make your code more robust.
- Use relative paths rather than absolute paths for portability.
- Prefer
pathlibfor modern, object-oriented handling of file paths. - Use specialized modules (
csv,json, etc.) rather than parsing formats manually.
Conclusion
File handling is an essential skill in Python programming. Whether you are working with simple text files, structured formats like CSV and JSON, or binary files, Python offers robust and flexible tools to meet your needs.
In this tutorial, we explored the basics of opening, reading, and writing files, as well as more advanced techniques for working with different formats and handling complex situations.
In the next tutorial, we will explore Python’s standard library, which includes many powerful modules for various tasks, including advanced file handling features.
Comments
Comments are powered by GitHub Discussions
Sign in with GitHub to join the discussion