4.1 Why do we need Files?
Every value that a Python program creates lives in RAM — the computer’s very fast but volatile memory. The moment your program ends (or the power is cut), RAM is wiped clean and the data is gone. For anything you want to keep — student marks, chat messages, photos, settings — you must save it on the disk, which keeps its contents even without power. The disk stores information in the form of files.
| Where | Speed | Capacity | Survives restart? |
|---|---|---|---|
| RAM (variables) | Very fast | GBs | No |
| Disk (files) | Slower | Hundreds of GB to TBs | Yes |
- Read — take existing data from the file into the program.
- Write — put new data from the program into a file (replacing whatever was there).
- Append — add new data at the end of an existing file.
4.2 What is a File?
Internally, every file is just a stream of bytes — zeros and ones. What makes a .txt look like readable words while a .jpg looks like random gibberish is the meaning each program assigns to those bytes. Python offers two different views of the same underlying stream:
- Text mode — bytes are decoded into human-readable characters (Unicode). Lines end with
\nand your program gets Python strings. - Binary mode — bytes are delivered raw, exactly as they are on the disk. Your program gets a
bytesobject.
4.3 Types of Files in Python
CBSE Class XII concentrates on three kinds of files:
4.3.1 Text Files
Store characters that you can read with any text editor (Notepad, VS Code, gedit). Every line ends with a newline character \n.
- Common extensions:
.txt,.py,.html,.log,.md. - Best for: notes, source code, configuration files, logs.
- Python tools: plain
open()in mode"r","w","a"— covered in Chapter 5.
4.3.2 Binary Files
Store raw bytes. Opening them in Notepad shows scrambled symbols. Your program reads and writes bytes exactly as they are; no character translation happens.
- Common extensions:
.jpg,.png,.mp3,.mp4,.exe,.dat,.pkl. - Best for: images, audio, video, machine-learning models, fast storage of Python objects.
- Python tools:
open()with a"b"in the mode ("rb","wb","ab") and thepicklemodule — covered in Chapter 6.
4.3.3 CSV Files (Comma-Separated Values)
A special kind of text file that stores tabular data — rows and columns — with a comma (or another separator) between columns.
- Common extensions:
.csv,.tsv. - Best for: spreadsheet data, exporting from / importing into Excel, quick data exchange.
- Python tools: the built-in
csvmodule (csv.reader,csv.writer) — covered in Chapter 7.
4.3.4 Side-by-side comparison
| Text file | Binary file | CSV file | |
|---|---|---|---|
| Human-readable? | Yes | No | Yes (basic tabular look) |
| Opened in Notepad? | Looks fine | Looks scrambled | Looks fine |
| Line ending | \n (converted by Python) | No concept of a “line” | \n |
Default mode in open | "r" / "rt" | "rb" | "r" + csv module |
| Data you read | str | bytes | list of strings per row |
| Typical use | Notes, logs, config | Images, audio, .pkl | Spreadsheet exchange |
4.4 File Paths — Where does Python look for the File?
Before your program can open a file, it needs to know where the file lives. That location is called a path.
4.4.1 Absolute vs. Relative paths
| Absolute path | Relative path | |
|---|---|---|
| Starts from | The root of the drive | The program’s current folder |
| Windows example | C:\Users\Vivek\notes\marks.txt | marks.txt or data\marks.txt |
| Linux / macOS example | /home/vivek/notes/marks.txt | marks.txt |
| Moves with your project? | No — breaks when copied | Yes — stays working |
.py file and refer to it by its name only — "marks.txt".
4.4.2 Backslashes on Windows — three safe ways
Windows uses \ as its path separator, but \ is also Python’s escape character. Pick any of these three safe forms:
4.5 Opening a File — the open() Function
open() asks the operating system for access to the file and returns a file object through which your program reads and writes data. If the file cannot be opened (missing, locked, no permission), Python raises an exception.
4.5.1 File Modes — what you plan to do
The mode is a short string telling Python whether you want to read, write, or append, and whether the file is text or binary.
| Mode | Full name | What it does |
|---|---|---|
"r" | Read (text) | Open existing file for reading. Default. Raises FileNotFoundError if the file does not exist. |
"w" | Write (text) | Create a new file or erase an existing one, then allow writing. ⚠ destroys old content. |
"a" | Append (text) | Open for writing at the end. Creates the file if missing; keeps old content intact. |
"x" | Exclusive create | Create a new file — fails (FileExistsError) if it already exists. |
"r+" | Read + Write | Read and write, file must exist, position starts at the beginning. |
"w+" | Write + Read | Like "w" (truncates) but also allows reading. |
"a+" | Append + Read | Like "a" but also allows reading. |
4.5.2 Text mode ("t") vs Binary mode ("b")
Add "b" to any of the modes above to switch to binary. The default is text ("t"). You can write the t explicitly if you like, but it is usually omitted.
| Mode string | Meaning |
|---|---|
"r" or "rt" | Read text (default) |
"w" or "wt" | Write text |
"rb" | Read binary |
"wb" | Write binary |
"ab" | Append binary |
"rb+" | Read + write binary |
"w" silently wipes out whatever the file already contained. If you meant to keep the old data, use "a" (append) instead.
4.5.3 The encoding argument — for text files
When a text file contains non-English characters (Hindi, emoji, accents), always say which encoding to use. The modern safe default is "utf-8".
4.6 Closing a File — f.close()
Every open() must be matched by a close(). Closing does three important things:
- Flushes any data still buffered in memory to the disk.
- Releases the file so other programs (or yours, on the next line) can use it.
- Frees the operating-system resource — open-file slots are limited.
4.7 The with Statement — the Preferred Way
with statement opens a file for you, runs your code, and guarantees the file is closed as soon as the block ends — even if an exception is raised inside.
Manual open / close | with statement | |
|---|---|---|
| Lines of code | More | Fewer |
| Forget to close? | Easy to forget | Impossible |
| Close on exception? | Needs try/finally | Automatic |
| CBSE preferred? | Acceptable | Recommended |
with open(…) as f:. It is shorter, safer, and the examiner will not deduct marks.
4.8 The File Object — what open() returns
open() gives you back a file object (also called a file handle or stream) that carries three useful pieces of information and the methods to read / write.
4.8.1 Preview of the methods (detailed in Ch 5–7)
| Method | Does |
|---|---|
f.read() | Read the entire file as one string |
f.read(n) | Read at most n characters / bytes |
f.readline() | Read one line (includes the trailing \n) |
f.readlines() | Read everything, return a list of lines |
f.write(s) | Write string s; returns the number of characters written |
f.writelines(lst) | Write every string in lst (no newlines added) |
f.tell() | Current position (bytes from start) |
f.seek(pos) | Jump to position pos |
f.flush() | Push buffered data to disk now |
f.close() | Close the file |
4.9 Common File-handling Exceptions
Files live outside your program, so every open/read/write can fail. These are the exceptions to know — and wrap in try / except (from Chapter 3).
| Exception | When it happens |
|---|---|
FileNotFoundError | Reading a file that doesn’t exist |
PermissionError | No read/write permission |
FileExistsError | Mode "x" on a file that already exists |
IsADirectoryError | Passed a folder name where a file was expected |
UnicodeDecodeError | Wrong encoding for the file’s actual content |
IOError / OSError | Generic input/output failure |
4.9.1 Using try / except with a file
4.10 Your First File-Handling Program
Before Chapter 5 dives into detail, here is a tiny program that writes two lines to a new file and then reads them back — so you can see the whole round-trip at once.
greeting.txt will be there. Open it in Notepad to confirm the data really sits on disk.
4.10.1 Append-mode variation
Change "w" to "a" and run again — the old two lines stay and two more lines are added at the end. Change back to "w", run, and the file is wiped to exactly two lines again. This is the difference between append and write in action.
4.11 Common Mistakes to Avoid
| # | Mistake | Fix |
|---|---|---|
| 1 | Using "w" when you wanted to add new data | Use "a" (append) — "w" wipes the file |
| 2 | Forgetting to close the file after writing | Prefer with open(…) as f: |
| 3 | Wrong path — FileNotFoundError | Check the current folder with import os; os.getcwd() |
| 4 | Single backslash in a Windows path | Use /, or a raw string r"C:\...", or double the \\ |
| 5 | Reading a binary file in text mode | Open with "rb" |
| 6 | Not wrapping open() in try/except | External failures (missing file, permission) are common |
| 7 | Ignoring the encoding on non-English files | Add encoding="utf-8" |
Quick-revision summary
- Variables live in RAM and vanish when the program ends; files live on disk and stay. This is data persistence.
- CBSE covers three file types: text (
.txt), binary (.jpg,.dat), and CSV (.csv). - Text mode returns
str; binary mode returnsbytes. Add"b"to any mode to switch. open(filename, mode)returns a file object. Modes:"r"read ·"w"write/truncate ·"a"append ·"x"exclusive · add"+"for read-and-write.- Relative paths are preferred. On Windows, use forward slashes or raw strings.
- Always close a file — best done automatically by
with open(…) as f:. - Wrap risky file operations in
try/except—FileNotFoundErrorandPermissionErrorare the most common.