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.
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
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 →