KwickAcademy Java · 6 min · free
File Handling
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
| Mode | Meaning | If file exists |
|---|---|---|
| "r" | read (default) | reads it |
| "w" | write | wipes it first |
| "a" | append | adds at the end |
| "x" | create new | FileExistsError |
| "rb", "wb" | read, write bytes | same, as bytes |
Text mode and binary mode
| Point | Text mode | Binary mode |
|---|---|---|
| Mode letters | r, w, a | rb, wb, ab |
| You get | str: characters | bytes: numbers |
| Used for | .txt, .csv | photos, PDF, music |
| Also called | character stream | byte stream |
When files go wrong
| Error | When it happens | Example |
|---|---|---|
| FileNotFoundError | file is missing | reading old.txt |
| PermissionError | not allowed | a locked file |
| IsADirectoryError | it is a folder | open("photos") |
| OSError | parent of all these | any 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.
Why is variable data lost?41 sec
What does w mode do to old text?40 sec
Which mode gives raw bytes?43 sec
Why does except OSError catch a missing file?38 secThe 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
| Course | Unit |
|---|---|
| CBSE Class 9 Information Technology (402) | Digital Presentation |
| ICSE Class 9 Computer Applications | Input 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 Studies | Basic Ubuntu Linux Commands |
| GSEB Std 12 Computer Studies | Exception Handling and File Handling in Java |
| NIOS Senior Secondary Data Entry Operations (336) | Lesson 10: Internet |
| Programming All levels Python | Projects and Applications |
| Programming All levels C | Introduction 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.

