File Handling in Python

PaketeLesen & Schreiben

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

Wir haben die Materialien überprüft, dennoch können Fehler vorkommen. Der Inhalt dient ausschließlich Bildungszwecken, daher verwende ihn auf eigene Verantwortung und überprüfe ihn bei Bedarf mit anderen Quellen.

✨ Frag Lara — deine KI-Lernpartnerin

Entsperre personalisierte Lernunterstützung. Lara kann Lektionen erklären, Themen zusammenfassen und deine Lernfragen beantworten — verfügbar ab dem Go-Tarif.


Lara hilft dir, schneller zu lernen — exklusiv für ReadyTools Go-, Plus- und Max-Mitglieder.

Verfolge deinen Fortschritt 🚀

Lerne einfacher, indem du deinen Fortschritt kostenlos verfolgst.