Skip to content
HackoryWEB SECURITY ACADEMYProgramming

Unit 12 · Archivos y JSON · Lesson 01

Leer un archivo de texto

open() y read() traen el contenido de un archivo.

Lesson content is in Spanish.

Python in your browser

The first time, Python downloads about 5 MB (only once; then it stays saved). If you can, use Wi-Fi.

Python is already saved in this browser: it will not download again.

Python downloads when you start reading.
  1. 01Understand
  2. 02Try
  3. 03Explain

The situation

Los datos de un programa no siempre están escritos en el código: muchas veces viven en archivos. En esta unidad, cada prueba crea los archivos que necesitás en un sistema de archivos de práctica, dentro del navegador.

Understand each piece

  • open(nombre, encoding="utf-8")

    Abre un archivo para leerlo. encoding="utf-8" indica cómo están guardadas las letras, para que las tildes se lean bien.

  • with ... as archivo:

    Usa el archivo abierto con el nombre archivo dentro del bloque con sangría. Al salir del bloque, Python lo cierra solo.

  • archivo.read()

    Devuelve todo el contenido del archivo como un texto.

Example

# Estas dos líneas crean un archivo de prueba (lo vas a ver en la lección 3)
with open("aviso.txt", "w", encoding="utf-8") as archivo:
    archivo.write("Sistema en mantenimiento")

with open("aviso.txt", encoding="utf-8") as archivo:
    texto = archivo.read()
print(texto)

Primero se crea el archivo aviso.txt. Después se abre para leer, read() guarda todo el contenido en texto y print lo muestra.

Before moving on: what will happen?

¿Qué va a mostrar este programa?
with open("nota.txt", "w", encoding="utf-8") as archivo:
    archivo.write("datos")

with open("nota.txt", encoding="utf-8") as archivo:
    texto = archivo.read()
print(texto.upper())

Your mission

Mostrá el aviso del día

La prueba crea un archivo llamado aviso.txt con un texto que puede terminar con un salto de línea. Leelo, quitale los espacios y saltos de línea de los bordes con strip() y mostrá estas tres líneas. Si el archivo dice Mañana abrimos a las 9, la salida es: Aviso del día: Mañana abrimos a las 9 Caracteres: 22

  1. with open("aviso.txt", encoding="utf-8") as archivo: y adentro texto = archivo.read().strip().
  2. Fuera del with: print("Aviso del día:") y print(texto).
  3. print(f"Caracteres: {len(texto)}").

If you get stuck

One hint at a time: the first points the way and the last almost solves it.

The key idea

with open(...) as archivo abre un archivo y lo cierra al terminar el bloque. read() devuelve todo su contenido.

Solve with help

If you have already tried, you can see a reference solution. The lesson is marked as solved with help and adds no XP.