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