intermediatePython Framework • Core Concepts

File Handling

Join 1.2k+ learners

Opening Files & Modes

Use `open(filename, mode)` to access files. Common modes: 'r' (read), 'w' (write, overwrites!), 'a' (append), 'x' (create). Add 'b' for binary files (e.g., 'rb' for images).

Python
# Read mode (default) f = open("data.txt", "r") # Write mode (careful, clears file!) f = open("output.txt", "w") # Append mode (adds to end) f = open("log.txt", "a")

File Modes

Start
if
Select Mode
'r': Read Only
'w': Overwrite
'a': Append
Start/End
Condition
Action

Reading Data

Use `.read()` for the whole file, `.readline()` for a single line, or `.readlines()` for a list of lines. Iterating over the file object is memory efficient.

Python
with open("story.txt", "r") as f: # Read entire content # content = f.read() # Best practice: Iterate line by line for line in f: print(line.strip()) # strip() removes \n

Writing & Appending

Use `.write()` to save string data. It does NOT add a newline automatically, so add `\n` manually. `.writelines()` writes a list of strings.

Python
lines = ["Entry 1\n", "Entry 2\n"] # 'w' clears existing content! with open("notes.txt", "w") as f: f.write("Title\n") f.writelines(lines) # 'a' adds to the end with open("notes.txt", "a") as f: f.write("Entry 3\n")

The 'with' Statement

Always use `with` (context manager) to open files. It acts as a safety net that automatically closes the file, even if your code crashes inside the block.

Python
try: with open("data.txt", "r") as f: data = f.read() # Auto-closed after this block except FileNotFoundError: print("File missing!") # No need for f.close() here

With Statement Magic

Start
Enter 'with'
Open File
Execute Block
Auto Close
Start/End
Condition
Action

Paths & Error Handling

Use `os.path` for handling file paths universally. Wrap operations in `try-except` to handle missing files (`FileNotFoundError`) or permission issues (`PermissionError`).

Python
import os filename = "config.ini" if os.path.exists(filename): try: with open(filename, "r") as f: print(f.read()) except PermissionError: print("Access denied!") else: print("File not found.")

Real-World: Logging

Applications use files to store logs. Appending ('a') is key here so you don't lose old history.

Python
import datetime def log_event(message): timestamp = datetime.datetime.now() entry = f"[{timestamp}] {message}\n" with open("app.log", "a") as log_file: log_file.write(entry) log_event("User logged in") log_event("Data export failed")

Master this concept

Hands-on practice is the fastest way to learn. Head over to our interactive workspace to solve this topic's challenge.

Launch Editor

Visual Lab

File Lifecycle

Start
open(file, mode)
if
Mode?
'r'
Read (r)
file.close()
'w', 'a'
Write (w/a)
file.close()
Start/End
Condition
Action

New Challenge available!

Master File Handling with a hands-on task.