CBSE 2026 results are out, Mukul scored a perfect 100/100 in Computer ScienceSee all toppers →

KwickAcademy Java · 6 min · free

File Handling

6 min4 KwickClipsFull text belowFree
Next lesson →Kajal Ma'am (MCA), teaching since 2004Remembered in this browser

Learn file handling in Python: why files, open() modes, reading and writing text, bytes, and handling file errors with try. A file is data saved on the disk, so it stays after the program ends, unlike variables in RAM.

Follows the syllabus of: CBSE Class 12 Computer Science (083)

On screen in this lesson

Why do we need files?

Variables live in RAM, which is wiped when the program ends
A file is saved on the disk, so it stays after closing
Files let programs share data with other programs
Examples: marks lists, bills, game high scores

open() and its modes

ModeMeaningIf file exists
"r"read (default)reads it
"w"writewipes it first
"a"appendadds at the end
"x"create newFileExistsError
"rb", "wb"read, write bytessame, as bytes

Text mode and binary mode

PointText modeBinary mode
Mode lettersr, w, arb, wb, ab
You getstr: charactersbytes: numbers
Used for.txt, .csvphotos, PDF, music
Also calledcharacter streambyte stream

When files go wrong

ErrorWhen it happensExample
FileNotFoundErrorfile is missingreading old.txt
PermissionErrornot alloweda locked file
IsADirectoryErrorit is a folderopen("photos")
OSErrorparent of all theseany file problem

Quick recap

Files keep data on disk after the program ends
open() modes: r reads, w wipes and writes, a appends
with closes the file for you
Text mode gives characters; binary mode gives bytes
Catch FileNotFoundError or OSError with try and except

Quick answers

What happens if you open a file in w mode twice?

The old content is wiped each time, so only the last write stays.

How do you stop a missing file from crashing the program?

Put the file code in try and catch FileNotFoundError or OSError with except.

KwickClips from this lesson

Short clips, one idea each. Good for revision the night before.

The full lesson, in text

Hello students, welcome to Kwickprep. You type the marks of forty students into a program, then close it. Where did the marks go? They are gone. Today we will learn to save data in files, read it back, handle text and bytes, and deal with file errors safely.

Variables are stored in RAM, the computer's working memory. RAM is cleared as soon as the program ends, so the data is lost. A file is data saved on the disk, the storage that keeps data even after the power goes off. Files also let one program pass data to another, like a spreadsheet opening your list. Mark sheets, shop bills and game high scores are all kept in files.

To use a file, Python gives the open function, with a file name and a mode. The read mode, written as the letter r, is used when you give no mode, and a missing file gives file not found error. The write mode, letter w, wipes the file clean first, or creates it if it is missing. The append mode, letter a, adds new text at the end. The create mode, letter x, makes a new file, but gives file exists error if the file is already there. Adding the letter b, for bytes, works with raw bytes instead of text.

The word with opens the file, and closes it for us when the block ends, even if an error happens. The phrase as f gives the open file a short name. Write puts text into the file, and backslash n means start a new line. Then we open the same file to read. A for loop gives one line at a time. Strip removes the new line at the end, so the output is clean.

There are other ways to read a file. Read, with nothing in the brackets, gives the whole file as one long string. Readline gives just the next line. Readlines gives a list, with one line in each place. Here the fee file has two lines, so the list length is two. Index zero is the first line, January fifteen hundred.

Pause and predict. We write Monday, then open the file again in write mode and write Tuesday. What does the file hold now? Only Tuesday. Every time you open in write mode, the old contents are wiped first. This is a very common exam question.

Now the same program, with one change. The second open uses a, for append. Append keeps the old text and adds the new text at the end. So the file now holds Monday Tuesday. Use append for things like an attendance log that grows every day.

Everything on a disk is really stored as bytes, and a byte is a number from zero to two hundred fifty five. Text mode uses the read, write and append letters, and binary mode adds the letter b. Text mode turns bytes into characters for you, while binary mode gives the raw numbers. Text mode suits text and C S V files, while binary mode suits photos, P D F files and music. Some textbooks call these a character stream and a byte stream.

We save Namaste as text, then read the same file in binary read mode. Python prints it with a small b in front, which means this is bytes, not a string. The list shows the first three bytes as numbers. Capital N is seventy eight, a is ninety seven, and m is one hundred nine. These numbers come from a code table that gives every character a number.

Files live outside your program, so things can go wrong. File not found error comes when you read a file that does not exist. Permission error comes when the computer does not allow you to use that file. Is a directory error comes when the name is a folder, not a file, though Windows may call it permission error. All of these belong to one family called O S error, which is Python's name for input output errors. Old code may say input output error, written IOError, which is simply another name for the same thing.

Without care, a missing file crashes the whole program. We put the risky lines inside a try block. If an error happens there, Python jumps to the matching except block instead of crashing. The file old marks does not exist, so file not found error happens. Our except block catches it and prints a friendly message.

Sometimes you want one except block for every file problem. Catch O S error, the parent, and it catches all its children too. As e gives the error a name, so we can look at it. The type function shows which child really happened, here file not found error. Never write an empty except that hides every error, because then bugs stay silent.

Let us revise what we learned today. Files keep data safe on the disk after the program ends. The read mode reads, the write mode wipes and writes, and the append mode adds to the end. The with block closes the file for you. Text mode gives characters, and binary mode gives raw bytes. And file problems are caught with try and except, using file not found error or O S error.

Courses that teach this

CourseUnit
CBSE Class 9 Information Technology (402)Digital Presentation
ICSE Class 9 Computer ApplicationsInput in Java
ISC Class 11 Computer Science (868)Elementary Data Structures and Implementation
ISC Class 12 Computer Science (868)Arrays and Strings
GSEB Std 11 Computer StudiesBasic Ubuntu Linux Commands
GSEB Std 12 Computer StudiesException Handling and File Handling in Java
NIOS Senior Secondary Data Entry Operations (336)Lesson 10: Internet
Programming All levels PythonProjects and Applications
Programming All levels CIntroduction to C and Program Structure

Voice-over in this lesson is AI-generated. The script is written and checked by Kajal Ma'am. Boards can revise a syllabus mid-year, so confirm anything you plan around against the official board circular. Keep your passwords, OTPs and ID numbers to yourself — we never ask for them. To reach Kajal Ma'am, use the WhatsApp button; sharing your number there is how we call you back.

Free to watch, no sign-up. Live classes with Kajal Ma'am are the paid course; these lessons stay free either way.

Want a plan that actually fits your board dates?

Ask Kajal Ma'am directly, 20+ years teaching computer science. Free demo class first, no payment.

Talk to Kajal Ma'am on WhatsApp

Or see the Class 12 Computer Science course →

Studying outside India?

We coach CBSE, IGCSE & international students across the globe, one-to-one, in your local time zone.

Visit International →