Ahora que entiendes cómo trabajar con rutas de archivos en Python, pongamos este conocimiento en práctica creando un simple administrador de archivos multiplataforma. Esta aplicación demostrará cómo realizar operaciones comunes de archivos mientras se garantiza la compatibilidad en diferentes sistemas operativos.
Configurar la estructura del proyecto
Primero, creemos una estructura de proyecto adecuada:
- Crea un nuevo directorio llamado
file_manager
:
mkdir -p /home/labex/project/file_manager
- Dentro de este directorio, crea un nuevo archivo llamado
app.py
:
touch /home/labex/project/file_manager/app.py
- Abre el archivo
app.py
en el editor y agrega el siguiente código:
import os
import shutil
from datetime import datetime
class FileManager:
def __init__(self, root_dir=None):
"""Initialize the file manager with a root directory."""
if root_dir is None:
self.root_dir = os.getcwd()
else:
self.root_dir = os.path.abspath(root_dir)
## Create a storage directory if it doesn't exist
self.storage_dir = os.path.join(self.root_dir, "storage")
if not os.path.exists(self.storage_dir):
os.makedirs(self.storage_dir)
print(f"Created storage directory: {self.storage_dir}")
def list_directory(self, directory=None):
"""List the contents of the specified directory."""
if directory is None:
directory = self.storage_dir
else:
## Convert relative path to absolute
if not os.path.isabs(directory):
directory = os.path.join(self.storage_dir, directory)
if not os.path.exists(directory):
print(f"Directory does not exist: {directory}")
return
if not os.path.isdir(directory):
print(f"Not a directory: {directory}")
return
print(f"\nContents of {directory}:")
items = os.listdir(directory)
if not items:
print(" (empty directory)")
return
for item in items:
item_path = os.path.join(directory, item)
item_stat = os.stat(item_path)
mod_time = datetime.fromtimestamp(item_stat.st_mtime).strftime('%Y-%m-%d %H:%M:%S')
if os.path.isdir(item_path):
print(f" 📁 {item} - Modified: {mod_time}")
else:
size = item_stat.st_size
if size < 1024:
size_str = f"{size} bytes"
elif size < 1024 * 1024:
size_str = f"{size/1024:.1f} KB"
else:
size_str = f"{size/(1024*1024):.1f} MB"
print(f" 🗒️ {item} - Size: {size_str} - Modified: {mod_time}")
def create_file(self, filename, content=""):
"""Create a new file with the given content."""
file_path = os.path.join(self.storage_dir, filename)
try:
with open(file_path, 'w') as f:
f.write(content)
print(f"Created file: {file_path}")
except Exception as e:
print(f"Error creating file: {e}")
def create_directory(self, dirname):
"""Create a new directory."""
dir_path = os.path.join(self.storage_dir, dirname)
try:
os.makedirs(dir_path, exist_ok=True)
print(f"Created directory: {dir_path}")
except Exception as e:
print(f"Error creating directory: {e}")
def delete_item(self, item_name):
"""Delete a file or directory."""
item_path = os.path.join(self.storage_dir, item_name)
if not os.path.exists(item_path):
print(f"Item does not exist: {item_path}")
return
try:
if os.path.isdir(item_path):
shutil.rmtree(item_path)
print(f"Deleted directory: {item_path}")
else:
os.remove(item_path)
print(f"Deleted file: {item_path}")
except Exception as e:
print(f"Error deleting item: {e}")
def move_item(self, source, destination):
"""Move a file or directory from source to destination."""
source_path = os.path.join(self.storage_dir, source)
dest_path = os.path.join(self.storage_dir, destination)
if not os.path.exists(source_path):
print(f"Source does not exist: {source_path}")
return
try:
shutil.move(source_path, dest_path)
print(f"Moved {source_path} to {dest_path}")
except Exception as e:
print(f"Error moving item: {e}")
## Main program to demonstrate the file manager
if __name__ == "__main__":
print("Cross-Platform File Manager")
print("===========================")
manager = FileManager()
## Create some test files and directories
manager.create_file("hello.txt", "Hello, world! This is a test file.")
manager.create_file("data.csv", "id,name,age\n1,Alice,28\n2,Bob,32")
manager.create_directory("documents")
manager.create_file("documents/notes.txt", "These are some notes in the documents folder.")
## List contents
manager.list_directory()
## Move a file
manager.move_item("hello.txt", "documents/hello.txt")
## List contents after move
print("\nAfter moving hello.txt to documents folder:")
manager.list_directory()
manager.list_directory("documents")
## Delete a file
print("\nDeleting data.csv file:")
manager.delete_item("data.csv")
manager.list_directory()
print("\nFile operations completed successfully!")
- Guarda el archivo.
Ejecutar la aplicación de administrador de archivos
Ahora, ejecutemos nuestra aplicación de administrador de archivos:
cd /home/labex/project
python3 file_manager/app.py
Deberías ver una salida que muestra varias operaciones de archivos:
- Crear archivos y directorios
- Listar el contenido de los directorios
- Mover archivos
- Eliminar archivos
Esta aplicación demuestra varios conceptos importantes para trabajar con archivos en diferentes plataformas:
- Usar
os.path.join()
para crear rutas de archivos
- Convertir entre rutas relativas y absolutas
- Trabajar con archivos y directorios
- Mover y eliminar archivos
- Manejar errores durante las operaciones de archivos
Ampliar la aplicación
Creemos un script más para demostrar cómo copiar archivos entre directorios:
- Crea un nuevo archivo llamado
file_operations.py
en el directorio del proyecto:
touch /home/labex/project/file_operations.py
- Agrega el siguiente código:
import os
import shutil
import platform
def print_system_info():
"""Print information about the current operating system."""
print(f"Operating System: {platform.system()}")
print(f"OS Version: {platform.version()}")
print(f"Python Version: {platform.python_version()}")
print(f"Path Separator: {os.path.sep}")
print(f"Current Directory: {os.getcwd()}")
def copy_file(source, destination):
"""Copy a file from source to destination."""
try:
## Ensure the destination directory exists
dest_dir = os.path.dirname(destination)
if dest_dir and not os.path.exists(dest_dir):
os.makedirs(dest_dir)
print(f"Created directory: {dest_dir}")
## Copy the file
shutil.copy2(source, destination)
print(f"Copied: {source} → {destination}")
## Get file info
file_size = os.path.getsize(destination)
print(f"File size: {file_size} bytes")
return True
except Exception as e:
print(f"Error copying file: {e}")
return False
## Main program
if __name__ == "__main__":
print("Cross-Platform File Operations")
print("==============================")
print_system_info()
## Create a test directory structure
base_dir = os.path.join(os.getcwd(), "test_copy")
if not os.path.exists(base_dir):
os.makedirs(base_dir)
source_dir = os.path.join(base_dir, "source")
dest_dir = os.path.join(base_dir, "destination")
if not os.path.exists(source_dir):
os.makedirs(source_dir)
if not os.path.exists(dest_dir):
os.makedirs(dest_dir)
## Create a test file
test_file = os.path.join(source_dir, "test.txt")
with open(test_file, 'w') as f:
f.write("This is a test file for copying operations.\n" * 10)
print(f"\nCreated test file: {test_file}")
## Copy the file to the destination
dest_file = os.path.join(dest_dir, "test_copy.txt")
copy_file(test_file, dest_file)
## Try copying to a nested directory that doesn't exist yet
nested_dest = os.path.join(dest_dir, "nested", "folders", "test_nested.txt")
copy_file(test_file, nested_dest)
print("\nFile operations completed!")
- Guarda el archivo.
- Ejecuta el script:
python3 file_operations.py
Este script demuestra:
- Obtener información del sistema (tipo de sistema operativo, separador de ruta)
- Crear estructuras de directorios de forma recursiva
- Copiar archivos entre directorios
- Manejar rutas anidadas que pueden no existir
La combinación de estos scripts muestra cómo se puede trabajar con archivos y directorios de una manera que funcione correctamente en diferentes sistemas operativos, lo cual es esencial para escribir aplicaciones portables de Python.