Home › coding › python › py file handling

Py File Handling — Free Python Tutorial

Learn Py File Handling in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

✓ 100% Free ✓ No Login Needed ✓ NCERT / CBSE Aligned ✓ Download as PDF

TL;DR: Learn Py File Handling in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.

Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated Jul 14, 2026

🤖 Stuck on any question? Ask Syllab's free AI Tutor for a step-by-step explanation — instant, unlimited, no login.

Py File Handling in Python

File handling lets Python programs read data from files and write results back — crucial for any real application. Data stored in variables is lost when the program ends; files persist permanently.

File modes: 'r' (read — default), 'w' (write — creates new or overwrites), 'a' (append — adds to existing), 'r+' (read and write). Always use 'w' carefully — it deletes existing content!

The with statement (context manager) is the recommended way to open files — it automatically closes the file even if an error occurs. Never skip this — unclosed files can corrupt data or cause permission errors.

Text files store data as strings. For more complex data, use JSON (for structured data) or CSV (for tabular data) — Python has built-in modules for both.

Py File Handling — Syntax

# File I/O patterns:
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()      # entire file
    # lines = f.readlines() # list of lines
    # for line in f: ...    # line by line

import csv, json
with open("data.csv", newline="") as f:
    reader = csv.DictReader(f)

Learn Py File Handling step by step with Syllab's free interactive Python tutorial — runnable code examples, practice exercises and instant AI feedback, all free with no signup. Explore the full Python course →

Explore:

  • Syllabus
  • Practice
  • Mock Tests
  • NCERT Solutions
  • Coding
  • GK Quiz
  • Career Predictor
  • AI Tutor
  • Live Quiz
  • Doubt Solver
  • Microlearning
  • Free Alternatives
  • Kids Zone
  • Study Room
  • Calculators
  • Worksheets

Syllab.in — Free learning for Indian students, Class 1–12