Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Variables, dictionaries, and lists created in Python live in RAM (Random Access Memory). RAM is volatile: as soon as your script finishes executing, the operating system reclaims the memory and all data vanishes.
To preserve data permanently across restarts, software systems rely on file handling (File I/O) to read from and write to non-volatile storage (SSDs or hard drives). In Python, working with files follows a three-step lifecycle:
+-------------------------------------------------------------------------------+
| FILE HANDLING REAL-WORLD ANALOGIES |
+-------------------------------------------------------------------------------+
1. THE STATE BANK STRONGROOM LEDGER:
- Step 1: The bank manager retrieves the physical loan ledger from the
vault (`open`).
- Step 2: An accountant records a new mortgage payment on the page (`write`).
- Step 3: The manager returns the book to the vault, locks the steel
door, and pockets the brass key (`close`).
- If the ledger is left open on the counter:
* Another branch clerk cannot access it (File Locking).
* Wind or tea spills could corrupt the records (Data Corruption).
* Unfinished penciled entries are never officially stamped (Unflushed Buffer).
2. THE GOVERNMENT HOSPITAL PATIENT FOLDER:
- Read Mode (`'r'`): Doctor opens folder to read previous blood reports.
- Append Mode (`'a'`): Doctor attaches today's prescription to the back.
- Write Mode (`'w'`): Hospital replaces the old folder entirely with a blank one!
+-------------------------------------------------------------------------------+open() Function & Access ModesFiles in Python are opened using the built-in open() function:
| Mode | Name | Behavior | Creates File If Missing? | Overwrites Existing? |
|---|---|---|---|---|
'r' | Read (Default) | Opens for reading. Pointer at the beginning. | NO (Raises FileNotFoundError) | No |
'w' | Write | Opens for writing. Truncates (erases) entire file! | YES | YES (Overwrites completely!) |
'a' | Append | Opens for writing. Pointer at the end. Preserves old data. | YES | NO (Appends to end) |
'x' | Exclusive Create | Creates a brand new file for writing. | YES | NO (Raises FileExistsError if file exists) |
'r+' | Read + Write | Opens for both reading and writing. | NO | No (Overwrites characters at pointer) |
'b' | Binary Mode | Raw byte stream for images, PDFs, MP3s (e.g. 'rb', 'wb'). | Mode dependent | Mode dependent |
't' | Text Mode (Default) | Decodes bytes to strings using character encodings (UTF-8). | Mode dependent | Mode dependent |
'w' Mode):'w' mode overwrites everything currently in the file. If the file does not exist, Python creates it automatically:
'a' Mode):'a' mode places the file pointer at the very end of the file, allowing you to add new lines without destroying existing records:
'r' Mode):Output:
file.close())?'x' Mode)When generating invoices or transaction tokens, you want to guarantee that you do not accidentally overwrite an existing customer's file. The 'x' mode guarantees safety:
| Best Practice (DO) | Dangerous Anti-Pattern (DON'T) |
|---|---|
DO specify encoding="utf-8" explicitly to prevent cross-platform text corruption. | DON'T use 'w' mode when you intend to add records to an existing file; 'w' erases past content! |
DO call file.close() as soon as your I/O operations finish. | DON'T leave files open inside long-running loops or server endpoints. |
DO use 'x' mode when creating files that must never overwrite existing data. | DON'T assume written data is physically saved before closing or calling flush(). |
open(filename, mode) connects your script to a physical file on disk.'r' reads an existing file (errors if not found); 'w' overwrites an existing file or creates a new one.'a' appends new data to the end of a file without destroying existing contents.'x' exclusively creates a new file, raising FileExistsError if the file already exists.file.close() to flush buffered data to disk and release operating system file locks.Always use the with open() context manager so files are automatically closed even if an exception occurs:
'w' ModeOpening an existing file in 'w' (write) mode immediately truncates (erases) all existing content! To preserve existing data and add to the end, use 'a' (append) mode.
A. 'r' B. 'a' C. 'w' D. 'x'
open("missing.txt", "r")?A. Python creates an empty file named "missing.txt" B. Python raises a FileNotFoundError C. Python returns None D. The script pauses until the file is manually created
'x' mode (exclusive creation) over 'w' mode?A. 'x' mode encrypts the file on disk B. 'x' mode raises a FileExistsError if the file already exists, protecting against accidental data overwrites C. 'x' mode runs 50% faster than 'w' D. 'x' mode is required for binary images
file.write() not immediately appear in the file on disk before file.close() is called?A. Python encrypts all files before writing B. Written data is held in an internal memory buffer in RAM and is only flushed to disk upon close or explicit flush C. The operating system only writes files at midnight D. file.write() is an asynchronous non-blocking thread
server.log file without losing past entries?A. 'r+' B. 'w' C. 'a' D. 'x'
Build an automated railway departure logging engine for the Station Master at Varanasi Junction (BSB).
initialize_station_log(filename):'w' mode to create a clean daily log header with Station Code, Date, and Column Titles ("Train No | Name | Destination | Dep Time").log_train_departure(filename, train_no, train_name, destination, dep_time):'a' mode to append an individual train departure entry to the log file.display_daily_station_manifest(filename):'r' mode to read the complete log from disk and display it to the console.In the next lesson, we will continue your Python learning journey with Reading & Writing Files (15: File Handling).
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Project: Calculator | Reading & Writing Files |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.