File Handling — Read, Write, CSV & JSON — Free Python Tutorial
Learn File Handling — Read, Write, CSV & JSON in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.in.
TL;DR: Learn File Handling — Read, Write, CSV & JSON in Python with a free, beginner-friendly tutorial, examples and practice for Indian students on Syllab.i…
Written & reviewed by the Syllab.in Academic Team (CBSE/NCERT subject experts) · Updated
File Handling — Read, Write, CSV & JSON 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.
File Handling — Read, Write, CSV & JSON — Syntax
# Reading a file
with open("filename.txt", "r", encoding="utf-8") as f:
content = f.read() # entire file as string
lines = f.readlines() # list of lines
line = f.readline() # one line at a time
# Writing a file
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello
")
f.writelines(["Line1
", "Line2
"])
Learn File Handling — Read, Write, CSV & JSON 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 →