File Handling
Learn to read from and write to files using Python.
📂 Introduction: The "Notebook" Analogy
Working with files in Python is exactly like working with a physical notebook.
1. Open: You must first open the notebook before you can use it.
2. Mode: You decide if you want to READ what's written, WRITE new things (erasing old ones), or APPEND new notes at the end.
3. Close: You must close the notebook when you are done so others can use it.
If you forget to close the file, it's like leaving the notebook open on your desk - it takes up space (memory) and might get damaged (corrupted).
📖 Topic 1: Opening and Reading
The open() function is the key. It takes the filename and the mode.
📊 File Modes:
'r'
Read (default)
Errors if file doesn't exist
'w'
Write
Overwrites ALL existing content!
'a'
Append
Adds content to the end
💡 The Context Manager (Best Practice):
Instead of manually closing files, use the with keyword. It automatically closes the file for you, even if your code crashes halfway through.
💻 Example: Reading Files
content = file.read()
print(content)
file.close() # Easy to forget!
✏️ Topic 2: Writing vs Appending
Be careful with Write mode! It's destructive.
Write Mode ('w')
If the file exists, it DELETES everything and starts fresh. If not, it creates a new file.
Append Mode ('a')
Keeps existing content and adds new text to the end of the file.
💻 Example: Write Operations
📄 Topic 3: Efficient Reading
What if your file is 10GB? If you use .read(), Python tries to load 10GB into RAM, and your computer freezes. Instead, iterate line by line.
💻 Example: Memory Efficient Loop
🖥️ Topic 4: Sandbox File Handling (io.StringIO)
Since this practice environment runs in a browser/sandbox, we cannot create real files on your hard drive. Instead, we use In-Memory Files.
io.StringIO creates a file that lives entirely in RAM. It behaves EXACTLY like a real file (it has .read(), .write(), etc.), making it perfect for practice.
💻 Example: Virtual Files
📚 Quick Cheat Sheet
open('file', 'r'): Read mode (default).open('file', 'w'): Write mode (Overwrites everything!).open('file', 'a'): Append mode (Adds to end).with open(...): Safely opens and auto-closes files.io.StringIO: Simulates files in memory for practice.
🤔 Interview Q&A
Tap on the questions below to reveal the answers.
Files consume system resources (like memory handles). If you don't close them, your operating system might run out of handles, preventing you from opening new files. It can also lead to data corruption if data wasn't fully saved.
The with statement acts as a Context Manager. It ensures that the file is properly closed as soon as the block of code finishes, even if an error occurs inside the block. It replaces the need for try...finally blocks for file handling.
In 'w' (write) mode, Python will create the file for you if it doesn't exist. However, if you open a non-existent file in 'r' (read) mode, Python will raise a FileNotFoundError.
You can use the file.readlines() method, which returns a list where every element is a line from the file. Alternatively, you can use list(file).