Principiantepython
Lectura y Escritura de Archivos
Aprende a leer, escribir y manipular archivos de texto y JSON en Python.
Abrir y leer archivos
La funcion
open() con el context manager with garantiza que el archivo se cierre correctamente.python
1# Leer todo el contenido
2with open("datos.txt", "r", encoding="utf-8") as f:
3 contenido = f.read()
4 print(contenido)
5
6# Leer linea por linea (eficiente en memoria)
7with open("datos.txt", "r") as f:
8 for linea in f:
9 print(linea.strip())Escribir archivos
Usa el modo
w para escribir (sobreescribe) o a para agregar al final (append).python
1# Escribir nuevo archivo
2with open("salida.txt", "w", encoding="utf-8") as f:
3 f.write("Primera linea\n")
4 f.write("Segunda linea\n")
5
6# Agregar al final
7with open("salida.txt", "a") as f:
8 f.write("Linea agregada\n")Trabajar con JSON
El modulo
json permite serializar y deserializar datos de forma sencilla.python
1import json
2
3# Escribir JSON
4datos = {"nombre": "Ana", "edad": 28, "skills": ["Python", "React"]}
5with open("perfil.json", "w") as f:
6 json.dump(datos, f, indent=2, ensure_ascii=False)
7
8# Leer JSON
9with open("perfil.json", "r") as f:
10 perfil = json.load(f)
11 print(perfil["nombre"])