Méthodes pour vérifier si un fichier est vide
Maintenant que nous avons nos fichiers de test, explorons différentes méthodes Python pour vérifier si un fichier est vide. Nous allons créer un script Python pour démontrer chaque approche.
Créez un nouveau fichier nommé check_empty.py
dans votre répertoire de projet en suivant ces étapes :
- Dans le WebIDE, cliquez sur l'icône "New File" dans le panneau Explorer
- Nommez le fichier
check_empty.py
et enregistrez-le dans le répertoire ~/project
- Copiez le code de chaque méthode au fur et à mesure que nous les parcourons
Méthode 1 : Utilisation de os.path.getsize()
La méthode la plus simple pour vérifier si un fichier est vide consiste à utiliser la fonction os.path.getsize()
du module os
. Cette fonction renvoie la taille d'un fichier en octets. Si le fichier est vide, elle renvoie 0
.
Ajoutez le code suivant à votre fichier check_empty.py
:
import os
def check_empty_using_getsize(file_path):
"""Check if a file is empty using os.path.getsize()"""
try:
if os.path.getsize(file_path) == 0:
return True
else:
return False
except OSError as e:
print(f"Error checking file: {e}")
return None
## Test with our files
empty_file = "/home/labex/project/empty_file.txt"
non_empty_file = "/home/labex/project/non_empty_file.txt"
print(f"Method 1: Using os.path.getsize()")
print(f"Is {empty_file} empty? {check_empty_using_getsize(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_getsize(non_empty_file)}")
print()
Méthode 2 : Utilisation de la méthode de lecture de fichier
Une autre approche consiste à ouvrir le fichier, à lire son contenu et à vérifier si quelque chose a été lu. Si le fichier est vide, sa lecture renverra une chaîne vide.
Ajoutez le code suivant à votre fichier check_empty.py
:
def check_empty_using_read(file_path):
"""Check if a file is empty by reading it"""
try:
with open(file_path, 'r') as file:
content = file.read()
if len(content) == 0:
return True
else:
return False
except IOError as e:
print(f"Error reading file: {e}")
return None
print(f"Method 2: Using file.read()")
print(f"Is {empty_file} empty? {check_empty_using_read(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_read(non_empty_file)}")
print()
Méthode 3 : Utilisation de os.stat()
La fonction os.stat()
fournit des informations détaillées sur un fichier, y compris sa taille. Vous pouvez vérifier l'attribut st_size
pour déterminer si le fichier est vide.
Ajoutez le code suivant à votre fichier check_empty.py
:
def check_empty_using_stat(file_path):
"""Check if a file is empty using os.stat()"""
try:
file_stats = os.stat(file_path)
if file_stats.st_size == 0:
return True
else:
return False
except OSError as e:
print(f"Error getting file stats: {e}")
return None
print(f"Method 3: Using os.stat()")
print(f"Is {empty_file} empty? {check_empty_using_stat(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_stat(non_empty_file)}")
print()
Méthode 4 : Utilisation du module pathlib
Le module pathlib
de Python fournit une approche orientée objet pour travailler avec les chemins de fichiers. Nous pouvons également l'utiliser pour vérifier si un fichier est vide.
Ajoutez le code suivant à votre fichier check_empty.py
:
from pathlib import Path
def check_empty_using_pathlib(file_path):
"""Check if a file is empty using pathlib.Path"""
try:
path = Path(file_path)
if path.stat().st_size == 0:
return True
else:
return False
except OSError as e:
print(f"Error checking file with pathlib: {e}")
return None
print(f"Method 4: Using pathlib")
print(f"Is {empty_file} empty? {check_empty_using_pathlib(empty_file)}")
print(f"Is {non_empty_file} empty? {check_empty_using_pathlib(non_empty_file)}")
Exécution du script
Exécutons maintenant notre script pour voir toutes les méthodes en action. Dans le terminal, exécutez :
python3 ~/project/check_empty.py
Vous devriez voir une sortie similaire à celle-ci :
Method 1: Using os.path.getsize()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 2: Using file.read()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 3: Using os.stat()
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Method 4: Using pathlib
Is /home/labex/project/empty_file.txt empty? True
Is /home/labex/project/non_empty_file.txt empty? False
Comme vous pouvez le constater, les quatre méthodes identifient correctement nos fichiers vides et non vides. Dans l'étape suivante, nous allons créer un script pratique qui utilise ces méthodes pour la gestion des fichiers.