VM-LEARNING /class.xii ·track.cs ·ch-1-4 session: 2026_27
$cd ..

~/Introduction to Files

root@vm-learning ~ $ open ch-1-4
UNIT 1 ▪ CHAPTER 4
04
Introduction to Files
Data Persistence · Text vs Binary vs CSV · File Paths · open() · Modes · close() · with-statement
A file is a named collection of data stored on a disk (hard-disk, SSD, pen-drive, memory card). Files let your program save data permanently so it is still there after the program ends or the computer is switched off.
Real-life analogy. The variables in a Python program are like your short-term memory — everything you put in them disappears when you stop thinking. A file is like a notebook — you write in it, close the notebook, come back tomorrow, and your notes are still there. This idea is called data persistence.

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.

WhereSpeedCapacitySurvives restart?
RAM (variables)Very fastGBsNo
Disk (files)SlowerHundreds of GB to TBsYes
Three things a program can do with a file:
  1. Read — take existing data from the file into the program.
  2. Write — put new data from the program into a file (replacing whatever was there).
  3. 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:

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.

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.

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.

name,marks,grade Asha,92,A1 Rahul,78,B1 Riya,85,A2

4.3.4 Side-by-side comparison

Text fileBinary fileCSV file
Human-readable?YesNoYes (basic tabular look)
Opened in Notepad?Looks fineLooks scrambledLooks 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 readstrbyteslist of strings per row
Typical useNotes, logs, configImages, audio, .pklSpreadsheet 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 pathRelative path
Starts fromThe root of the driveThe program’s current folder
Windows exampleC:\Users\Vivek\notes\marks.txtmarks.txt or data\marks.txt
Linux / macOS example/home/vivek/notes/marks.txtmarks.txt
Moves with your project?No — breaks when copiedYes — stays working
Use relative paths in your CBSE programs. Place the data file in the same folder as your .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:

path1 = "C:/Users/Vivek/data/marks.txt" # forward slashes (always safe) path2 = r"C:\Users\Vivek\data\marks.txt" # raw string — \ is literal path3 = "C:\\Users\\Vivek\\data\\marks.txt" # escape each backslash

4.5 Opening a File — the open() Function

file_object = open(filename, mode)

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.

f = open("marks.txt", "r") # open for reading # … use the file … f.close() # always close when done

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.

ModeFull nameWhat 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 createCreate a new file — fails (FileExistsError) if it already exists.
"r+"Read + WriteRead and write, file must exist, position starts at the beginning.
"w+"Write + ReadLike "w" (truncates) but also allows reading.
"a+"Append + ReadLike "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 stringMeaning
"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".

f = open("names.txt", "r", encoding="utf-8")

4.6 Closing a File — f.close()

Every open() must be matched by a close(). Closing does three important things:

  1. Flushes any data still buffered in memory to the disk.
  2. Releases the file so other programs (or yours, on the next line) can use it.
  3. Frees the operating-system resource — open-file slots are limited.
If you forget to close a file that you wrote to, some or all of the data may be lost — because it was still sitting in a memory buffer waiting to be flushed.

4.7 The with Statement — the Preferred Way

The 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.
with open("marks.txt", "r") as f: data = f.read() print(data) # f is automatically closed here — no f.close() needed
Manual open / closewith statement
Lines of codeMoreFewer
Forget to close?Easy to forgetImpossible
Close on exception?Needs try/finallyAutomatic
CBSE preferred?AcceptableRecommended
From now on, open every file with 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.

f = open("marks.txt", "r") print(f.name) # 'marks.txt' print(f.mode) # 'r' print(f.closed) # False f.close() print(f.closed) # True

4.8.1 Preview of the methods (detailed in Ch 5–7)

MethodDoes
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).

ExceptionWhen it happens
FileNotFoundErrorReading a file that doesn’t exist
PermissionErrorNo read/write permission
FileExistsErrorMode "x" on a file that already exists
IsADirectoryErrorPassed a folder name where a file was expected
UnicodeDecodeErrorWrong encoding for the file’s actual content
IOError / OSErrorGeneric input/output failure

4.9.1 Using try / except with a file

try: with open("marks.txt", "r") as f: print(f.read()) except FileNotFoundError: print("File does not exist yet.") except PermissionError: print("Not allowed to read this 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.

# 1) Write with open("greeting.txt", "w") as f: f.write("Hello, CBSE!\n") f.write("Welcome to file handling.\n") # 2) Read back with open("greeting.txt", "r") as f: contents = f.read() print(contents)
Hello, CBSE! Welcome to file handling.
After running this program, look at your project folder — 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

#MistakeFix
1Using "w" when you wanted to add new dataUse "a" (append) — "w" wipes the file
2Forgetting to close the file after writingPrefer with open(…) as f:
3Wrong path — FileNotFoundErrorCheck the current folder with import os; os.getcwd()
4Single backslash in a Windows pathUse /, or a raw string r"C:\...", or double the \\
5Reading a binary file in text modeOpen with "rb"
6Not wrapping open() in try/exceptExternal failures (missing file, permission) are common
7Ignoring the encoding on non-English filesAdd 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 returns bytes. 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/exceptFileNotFoundError and PermissionError are the most common.
🧠Practice Quiz — test yourself on this chapter