Text files · Archivos de texto
Why files?
- Variables vanish when a program ends. A file keeps data on disk.
- Files let you save results and read them back later.
- They also hold more data than you would type by hand.
¿Por qué archivos?
- Las variables desaparecen cuando termina un programa. Un archivo mantiene los datos en el disco.
- Los archivos te permiten guardar resultados y leerlos más adelante.
- También pueden contener más datos de los que escribirías manualmente.
Open, use, close
open(name, mode)opens a file. The mode says what you will do."r"reads,"w"writes a fresh file (replacing any old text),"a"adds to the end.- Every file you open must be closed when you finish.
Abrir, usar, cerrar
open(name, mode)abre un archivo. El modo indica lo que harás con él."r"para leer,"w"para escribir en un archivo nuevo (reemplazando cualquier texto anterior),"a"para añadir al final.- Todo archivo que abras debe ser cerrado cuando termines de usarlo.
The with block
with open(...) as f:opens the file and closes it for you.- All the work goes in the indented block.
- This is the safest way — the file is never left open.
Bloque with
with open(...) as f:abre el archivo y lo cierra por ti.- Todo el trabajo se realiza dentro del bloque indentado.
- Esta es la forma más segura: el archivo nunca queda abierto accidentalmente.
with open("greeting.txt", "w") as f:
f.write("Hi there\n")
with open("greeting.txt", "r") as f:
print(f.read())
Reading the lines
f.read()returns the whole file as one string.for line in f:reads it one line at a time.- Each line keeps its newline, so use
line.strip()to remove it.
Leer líneas
f.read()devuelve todo el archivo como una sola cadena.for line in f:lo lee una línea a la vez.- Cada línea conserva su salto de línea, así que usa
line.strip()para eliminarlo.
with open("fruit.txt", "w") as f:
f.write("apple\npear\n")
with open("fruit.txt", "r") as f:
for line in f:
print(line.strip())
In Cambridge pseudocode
- The exam uses
OPENFILE,WRITEFILE,READFILE, andCLOSEFILE.
En pseudocódigo de Cambridge
- El examen utiliza
OPENFILE,WRITEFILE,READFILEyCLOSEFILE.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
OPENFILE "notes.txt" FOR READ
READFILE "notes.txt", line
CLOSEFILE "notes.txt"
OUTPUT line
Common mistakes
- Use
with open(...) as f:so the file closes itself. "w"erases the file first;"a"adds to the end.
Errores comunes
- Usa
with open(...) as f:para que el archivo se cierre automáticamente. "w"borra el archivo primero;"a"añade al final.
Now you try
- This playground keeps files between runs, so write the file first, then read it in the same task.
- Press Check answer to test your code.
Ahora tú lo intentas
- Este entorno de práctica conserva los archivos entre ejecuciones, así que escribe el archivo primero, luego léelo en la misma tarea.
- Pulsa Check answer para probar tu código.
Reading a file · Leer un archivo
A file is used in three steps: open, read, close. · Un archivo se utiliza en tres pasos: abrir, leer, cerrar.
In one run: write the two lines Hello and · y World to a file called notes.txt, then open it again, read it, and print what you read. · En una ejecución: escribe las dos líneas Hello y World en un archivo llamado notes.txt, luego ábrelo nuevamente, léelo e imprime lo que leíste con print.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write three lines to a file, then read it back and count the lines with a loop. Store the count in count (the answer is 3). · Escribe tres líneas a un archivo, luego léelo de nuevo y cuenta las líneas con un bucle. Almacena el conteo en count (la respuesta es 3).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write the numbers 10, 20, 30 to a file, one per line. Then read them back, convert each line with int(...), and add them up in total (the answer is 60). · Escribe los números 10, 20, 30 a un archivo, uno por línea. Luego léelos de nuevo, convierte cada línea con int(...) y súmalos en total (la respuesta es 60).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.