File Handling in Python Class 12
File handling lets a Python program store data permanently on disk instead of losing it when the program closes. This is part of the Class 12 syllabus and ...
Why File Handling Matters
File handling lets a Python program store data permanently on disk instead of losing it when the program closes. This is part of the Class 12 syllabus and is essential for projects that keep records. Python works with two kinds of files: text files, which store readable characters line by line, and binary files, which store data in the computer's own format and are read using the pickle module. CSV files are a special text format used for tables of data.
Opening, Reading and Writing
You open a file with open(filename, mode). Common modes are 'r' to read, 'w' to write (which erases existing content), 'a' to append, and 'b' added for binary like 'rb'. After opening you can use read(), readline() or readlines() to read, and write() to write. Always close the file with close(), or better, use the with statement: with open('data.txt', 'r') as f: which closes the file automatically even if an error occurs. For binary files, pickle.dump() writes objects and pickle.load() reads them back.
Example and Exam Tip
Example: with open('marks.txt', 'a') as f: f.write('Ravi 88\n') adds one line to the file without deleting old data. Exam tip: board questions often ask you to write a program that counts the number of lines, words, or specific characters in a text file, or to read a CSV and display selected rows. Remember that 'w' mode destroys old data while 'a' preserves it - mixing these up is a common mistake that loses marks. Always mention closing the file or using with.