File Handling in Python

PaquetesLectura y escritura

Files are how programs store and retrieve data permanently – think of saving high scores in a game, reading configuration settings, or processing large datasets.

Python makes file handling simple and safe. The key function is open(), and the recommended way is using the with statement (context manager) which automatically closes the file.

We'll cover everything step by step: opening files in different modes, basic reading and writing, and important best practices.

The open() Function and File Modes

open(filename, mode) returns a file object. Common modes:

  • 'r' – read (default)
  • 'w' – write (creates new or overwrites)
  • 'a' – append (adds to end)
  • 'x' – exclusive creation (fails if exists)
  • 'b' – binary mode
  • 't' – text mode (default)
  • '+' – read and write

Why Use 'with open'?

It automatically closes the file even if an error occurs – preventing resource leaks and file corruption.

Writing to Files

Use write() for single string, writelines() for list of strings.

Reading from Files

read() reads everything, readline() one line, readlines() all lines into list.

Appending to Files

Quick Quiz

Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.

✨ Pregunta a Lara — tu compañera de estudio con IA

Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.


Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

Sigue Tu Progreso 🚀

Aprende más fácilmente siguiendo tu progreso completamente gratis.