Text files · Archivos de texto
Files keep data
- Variables vanish when a program ends; a file stores data so it lasts.
- The exam covers reading from and writing to text files.
- Work in three steps: open, read or write, then close.
Los archivos mantienen los datos
- Las variables desaparecen cuando termina un programa; un archivo almacena datos para que perduren.
- El examen cubre la lectura y escritura en archivos de texto.
- Se trabaja en tres pasos: abrir, leer o escribir, y luego cerrar.
Writing to a file
open(name, "w")opens a file for writing ("w"overwrites what was there).withcloses the file automatically when the block ends.\nstarts a new line in the file.
Escritura en un archivo
open(name, "w")abre un archivo para escribir ("w"sobrescribe lo que había).withcierra el archivo automáticamente al finalizar el bloque.\ninicia una nueva línea en el archivo.
with open("notes.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")
Reading a file
open(name, "r")opens a file for reading..read()pulls in the whole contents as one string.
Lectura de un archivo
open(name, "r")abre un archivo para leer..read()extrae todo el contenido como una sola cadena.
with open("notes.txt", "r") as f:
text = f.read()
print(text)
Reading line by line
- Looping over the file gives one line at a time — handy for totalling or counting.
Lectura línea por línea
- Iterar sobre el archivo proporciona una línea a la vez — útil para sumar totales o contar.
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
In the exam: file handling
- Pseudocode opens a file for a mode, reads or writes, then closes it.
En el examen: manejo de archivos
- La pseudocódigo abre un archivo para un modo, lee o escribe, y luego lo cierra.
OPENFILE "notes.txt" FOR WRITE
WRITEFILE "notes.txt", "Hello"
CLOSEFILE "notes.txt"
Common mistakes
- Open, then read or write, then close the file.
- A line you read still carries its newline character.
Errores comunes
- Abrir, luego leer o escribir, y finalmente cerrar el archivo.
- Una línea que se lee aún conserva su carácter de salto de línea.
Now you try
- Write a file, then open it again to read it back.
- Press Check answer to test your code.
Ahora tú intentas
- Escribe un archivo, luego ábrelo nuevamente para leerlo de vuelta.
- Presiona Comprobar respuesta para probar tu código.
Using a file · Usar un archivo
A file is used in three steps: open, read or write, close. · Un archivo se usa en tres pasos: abrir, leer o escribir, cerrar.
In one run: write the line Cambridge to a file called school.txt, then open it again, read it, and print what you read. · En una sola ejecución: escribe la línea Cambridge en un archivo llamado school.txt, luego ábrelo nuevamente, léelo e imprime lo que leíste usando print.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
The starter writes three lines to a file. Read it back and count the lines with a loop. Store the count in count (the answer is 3). · El código inicial escribe tres líneas a un archivo. Léalas 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í.
The starter writes 10, 20, 30 to a file, one per line. Read them back, convert each line with int(...), and add them up in total (the answer is 60). · El código inicial escribe 10, 20, 30 a un archivo, uno por línea. Léalos 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í.