Entrada/Salida de Archivos
## Objetivos de Aprendizaje
- Leer de y escribir en archivos
- Trabajar con diferentes modos de archivo
- Manejar rutas de archivos
- Usar context managers
## Abrir Archivos
### Sintaxis Básica
```python
archivo = open("nombre_archivo.txt", "r") # Abrir para lectura
contenido = archivo.read()
archivo.close()
```
### Modos de Archivo
| Modo | Descripción |
|------|-------------|
| `r` | Lectura (por defecto) |
| `w` | Escritura (sobrescribe) |
| `a` | Añadir |
| `x` | Crear (falla si existe) |
| `b` | Modo binario |
| `+` | Lectura y escritura |
```python
# Modos de texto
archivo = open("archivo.txt", "r") # Leer texto
archivo = open("archivo.txt", "w") # Escribir texto
archivo = open("archivo.txt", "a") # Añadir texto
archivo = open("archivo.txt", "x") # Crear texto
# Modos binarios
archivo = open("imagen.png", "rb") # Leer binario
archivo = open("salida.png", "wb") # Escribir binario
```
## Leer Archivos
### read()
```python
archivo = open("archivo.txt", "r")
contenido = archivo.read() # Leer archivo completo
archivo.close()
# Con codificación
archivo = open("archivo.txt", "r", encoding="utf-8")
```
### readline()
```python
archivo = open("archivo.txt", "r")
linea1 = archivo.readline() # Primera línea
linea2 = archivo.readline() # Segunda línea
archivo.close()
```
### readlines()
```python
archivo = open("archivo.txt", "r")
lineas = archivo.readlines() # Lista de todas las líneas
archivo.close()
# O iterar directamente
for linea in open("archivo.txt", "r"):
print(linea.strip())
```
## Escribir Archivos
### write()
```python
archivo = open("salida.txt", "w")
archivo.write("¡Hola, Mundo!\n")
archivo.write("Segunda línea")
archivo.close()
```
### writelines()
```python
lineas = ["Línea 1\n", "Línea 2\n", "Línea 3\n"]
archivo = open("salida.txt", "w")
archivo.writelines(lineas)
archivo.close()
```
## Context Managers (Recomendado)
### Usar Declaración with
```python
# Cierra el archivo automáticamente
with open("archivo.txt", "r") as archivo:
contenido = archivo.read()
print(contenido)
# El archivo se cierra automáticamente aquí
with open("salida.txt", "w") as archivo:
archivo.write("¡Hola!\n")
archivo.write("¡Mundo!")
# El archivo se cierra automáticamente aquí
```
### Múltiples Archivos
```python
with open("entrada.txt", "r") as entrada, open("salida.txt", "w") as salida:
for linea in entrada:
salida.write(linea.upper())
```
## Rutas de Archivos
### Manejo de Rutas
```python
import os
# Directorio actual
print(os.getcwd())
# Unir rutas
ruta = os.path.join("carpeta", "subcarpeta", "archivo.txt")
print(ruta) # carpeta/subcarpeta/archivo.txt
# Obtener partes
print(os.path.basename("/ruta/a/archivo.txt")) # archivo.txt
print(os.path.dirname("/ruta/a/archivo.txt")) # /ruta/a
print(os.path.splitext("/ruta/a/archivo.txt")) # ('/ruta/a/archivo', '.txt')
```
### Pathlib (Moderno)
```python
from pathlib import Path
# Crear ruta
p = Path("carpeta", "archivo.txt")
# Verificar
print(p.exists())
print(p.is_file())
print(p.is_dir())
# Leer/Escribir
contenido = p.read_text()
p.write_text("¡Hola!")
# Listar directorio
for item in Path(".").iterdir():
print(item.name)
# Glob
for py_file in Path(".").glob("*.py"):
print(py_file)
```
## Leer Archivos CSV
### Módulo csv
```python
import csv
# Lectura
with open("datos.csv", "r", newline="") as csvfile:
lector = csv.reader(csvfile)
for fila in lector:
print(fila)
# Leer como dict
with open("datos.csv", "r", newline="") as csvfile:
lector = csv.DictReader(csvfile)
for fila in lector:
print(fila["nombre"], fila["edad"])
```
### Escribir CSV
```python
import csv
with open("salida.csv", "w", newline="") as csvfile:
escritor = csv.writer(csvfile)
escritor.writerow(["Nombre", "Edad"])
escritor.writerow(["Ana", 25])
escritor.writerow(["Bob", 30])
# Escribir dicts
with open("salida.csv", "w", newline="") as csvfile:
campos = ["Nombre", "Edad"]
escritor = csv.DictWriter(csvfile, fieldnames=campos)
escritor.writeheader()
escritor.writerow({"Nombre": "Ana", "Edad": 25})
```
## Leer JSON
### Módulo json
```python
import json
# Lectura
with open("datos.json", "r") as jsonfile:
datos = json.load(jsonfile)
print(datos["nombre"])
# Escritura
datos = {"nombre": "Ana", "edad": 25, "ciudades": ["Madrid", "Barcelona"]}
with open("salida.json", "w") as jsonfile:
json.dump(datos, jsonfile, indent=2)
# Pretty print
print(json.dumps(datos, indent=2))
```
## Trabajar con Archivos Binarios
### Lectura
```python
with open("imagen.png", "rb") as archivo:
datos = archivo.read()
print(f"Leídos {len(datos)} bytes")
```
### Copiar un Archivo
```python
with open("origen.png", "rb") as origen, open("destino.png", "wb") como destino:
destino.write(origen.read())
```
## Información de Archivo
```python
import os
# Verificar existencia
print(os.path.exists("archivo.txt"))
# Tamaño de archivo
print(os.path.getsize("archivo.txt"), "bytes")
# Tiempo de modificación
import datetime
mtime = os.path.getmtime("archivo.txt")
print(datetime.datetime.fromtimestamp(mtime))
```
## Patrones Comunes
### Leer Todas las Líneas
```python
with open("archivo.txt", "r") como archivo:
lineas = archivo.readlines()
# O
with open("archivo.txt", "r") como archivo:
lineas = archivo.read().splitlines()
```
### Filtrar Líneas
```python
with open("archivo.txt", "r") como archivo:
filtradas = [linea.strip() for linea in archivo if "patrón" in linea]
```
### Añadir a Archivo
```python
with open("registro.txt", "a") como archivo:
archivo.write("Nueva entrada de registro\n")
```
## Resumen
- Abrir archivos con `open(nombre_archivo, modo)`
- Siempre usar context manager (`with`)
- Modos: `r`, `w`, `a`, `x`, `b`, `+`
- Leer: `read()`, `readline()`, `readlines()`
- Escribir: `write()`, `writelines()`
- Usar `pathlib.Path` para manejo moderno de rutas
- Usar módulos `csv` y `json` para archivos estructurados
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →