Python•File Handling
Python File Handling: Reading, Writing, and with open()
Python manages file descriptors cleanly using with open(filename, mode) as f, which guarantees automatic closing even if errors occur.
Syntax
with open(filename, mode, encoding="utf-8") as file:
content = file.read()
Parameters & Values
Key components and acceptable values for this structure:
| Parameter | Type | Description |
|---|---|---|
| filename | str / Path | Path to the target file on disk. |
| mode | str | "r" (read), "w" (write/overwrite), "a" (append), "rb" (binary). |
Ready-to-Run Code Example
Executable in CompilraRun this complete, working example directly without installing Python locally:
# In-memory File Simulation & io.StringIO
import io
# Simulating file read/write using Python in-memory buffers
virtual_file = io.StringIO()
# Writing content with context manager semantics
virtual_file.write("LOG: 2026-10-18 10:00:00 Server Initialized\n")
virtual_file.write("LOG: 2026-10-18 10:05:00 Database Connected\n")
virtual_file.write("LOG: 2026-10-18 10:10:00 Health Check PASSED\n")
# Reset buffer pointer to beginning
virtual_file.seek(0)
# Reading lines sequentially
print("--- Reading Virtual Log File ---")
for line_number, line in enumerate(virtual_file, start=1):
print(f"Line {line_number}: {line.strip()}")Expected Output:
--- Reading Virtual Log File --- Line 1: LOG: 2026-10-18 10:00:00 Server Initialized Line 2: LOG: 2026-10-18 10:05:00 Database Connected Line 3: LOG: 2026-10-18 10:10:00 Health Check PASSED
How It Works: Step-by-Step
- Lines 7-10: Writes multiple lines into the stream buffer.
- Line 13: seek(0) rewinds the read pointer back to the start of the file.
- Lines 16-18: Iterates through file stream line-by-line efficiently.
Key Concepts
- The with statement creates a context manager that calls file.close() automatically upon exit.
- Mode "w" overwrites existing file content; mode "a" appends new lines to the bottom.
- Iterating over a file object directly reads lazily line-by-line, conserving memory for large files.
Common Mistake: Opening files without using the with statement
Omitting with leaves file handles open on disk if an exception interrupts execution before close().
❌ Incorrect
f = open("log.txt", "w")
f.write("data") # If error happens here, f is never closed!
f.close()✅ Correct
with open("log.txt", "w") as f:
f.write("data") # Automatically closed safelyRelated Python Tutorials & Compiler
Python Async/Await and asyncio Concurrency Fundamentals
Learn how to write asynchronous concurrent code using Python async def, await, and the asyncio library.
Python Exception Handling: try, except, else, and finally
Exceptions in Python are handled gracefully using try...except blocks to catch runtime errors without crashing.
Python Strings: Slicing, Escaping, and Built-in Methods
Strings in Python are immutable sequences of Unicode characters with rich built-in transformation methods.
Python Online Compiler
Open in Compilra IDE
Run and test Python on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.