Métodos para Verificar si un Archivo está Vacío
Ahora que tenemos nuestros archivos de prueba, exploremos diferentes métodos de Python para verificar si un archivo está vacío. Crearemos un script de Python para demostrar cada enfoque.
Crea un nuevo archivo llamado check_empty.py en tu directorio del proyecto siguiendo estos pasos:
- En el WebIDE, haz clic en el icono "New File" (Nuevo Archivo) en el panel del Explorador.
- Nombra el archivo
check_empty.py y guárdalo en el directorio ~/project.
- Copia el código de cada método a medida que los revisamos.
Método 1: Usando os.path.getsize()
La forma más directa de verificar si un archivo está vacío es usar la función os.path.getsize() del módulo os. Esta función devuelve el tamaño de un archivo en bytes. Si el archivo está vacío, devuelve 0.
Agrega el siguiente código a tu archivo 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étodo 2: Usando el Método de Lectura de Archivos
Otro enfoque es abrir el archivo, leer su contenido y verificar si se leyó algo. Si el archivo está vacío, leerlo devolverá una cadena vacía.
Agrega el siguiente código a tu archivo 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étodo 3: Usando os.stat()
La función os.stat() proporciona información detallada sobre un archivo, incluido su tamaño. Puedes verificar el atributo st_size para determinar si el archivo está vacío.
Agrega el siguiente código a tu archivo 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étodo 4: Usando el módulo pathlib
El módulo pathlib de Python proporciona un enfoque orientado a objetos para trabajar con rutas de archivos. Podemos usarlo para verificar si un archivo está vacío también.
Agrega el siguiente código a tu archivo 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)}")
Ejecutando el Script
Ahora ejecutemos nuestro script para ver todos los métodos en acción. En la terminal, ejecuta:
python3 ~/project/check_empty.py
Deberías ver una salida similar a esta:
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
Como puedes ver, los cuatro métodos identifican correctamente nuestros archivos vacíos y no vacíos. En el siguiente paso, crearemos un script práctico que utiliza estos métodos para la gestión de archivos.