File Handling in Python

CsomagokOlvasás és írás

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

Az anyagokat átnéztük és ellenőriztük, de hibák továbbra is előfordulhatnak. A tartalom kizárólag oktatási célt szolgál, ezért saját felelősségre használd, és szükség esetén ellenőrizd más forrásokkal is.

✨ Kérdezd Larát — a tanulási partnered

Fedezd fel a személyre szabott tanulási támogatást. Lara elmagyarázza az anyagot, összefoglalja a témákat és megválaszolja a kérdéseidet — az Go csomagtól elérhető.


Lara segít gyorsabban tanulni — kizárólag a ReadyTools Go, Plus és Max tagoknak.

Kövesd nyomon a fejlődésed 🚀

Tanulj egyszerűbben utad nyomonkövetésével teljesen ingyen.