DSPython Logo DSPython

File Handling

Learn to read from and write to files using Python.

Python Basics Beginner 30 min

📂 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

# The BAD way (Don't do this)
file = open("data.txt", "r")
content = file.read()
print(content)
file.close() # Easy to forget!

# The GOOD way (Context Manager)
with open("data.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed here

✏️ 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

# 1. Overwrite file (All previous data lost!)
with open("notes.txt", "w") as f:
f.write("This is brand new content.")

# 2. Append to file (Safe addition)
with open("notes.txt", "a") as f:
f.write("\nPS: Don't forget to buy milk.")

📄 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

with open("huge_log_file.txt", "r") as file:
# This reads one line at a time into memory
for line in file:
if "ERROR" in line:
print(line.strip())

🖥️ 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

import io

# 1. Create a virtual file with some text
fake_file = io.StringIO("Hello World\nThis is a virtual file.")

# 2. Read from it like a normal file
print(fake_file.read())

# 3. Write to it
fake_file.write("\nAdded line.")

# 4. Get everything back
print(fake_file.getvalue())

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