Python
Module 9: Python File HandlingBeginner18 min read

Reading & Writing Files

Open files safely with context managers (with open) in read, write, and append modes.

Key Takeaways & Core Concepts
  • 'r' : Read (default). Opens file for reading; error if file does not exist.
  • 'w' : Write. Opens file for writing; creates file if missing or truncates existing content.
  • 'a' : Append. Opens file for appending to end; creates file if missing.
  • 'r+' : Read and write.

Reading & Writing Files

### File Handling in Python

Python has built-in functions for creating, reading, updating, and deleting files.

#### File Modes:

  • 'r' : Read (default). Opens file for reading; error if file does not exist.
  • 'w' : Write. Opens file for writing; creates file if missing or truncates existing content.
  • 'a' : Append. Opens file for appending to end; creates file if missing.
  • 'r+' : Read and write.

#### The Safe Way: with open() Always use context managers (with statement) because they automatically close the file stream even if an unexpected exception occurs:

PYTHON Code Example
1# Writing to a file
2with open("students.txt", "w", encoding="utf-8") as f:
3 f.write("Alice, Grade A\n")
4 f.write("Bob, Grade B+\n")
5
6# Reading lines from a file
7with open("students.txt", "r", encoding="utf-8") as f:
8 for line in f:
9 print(line.strip())
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Simulated File Processing
1content = """User: admin, Status: active
2User: guest, Status: inactive
3User: ashutosh, Status: active"""
4
5active_users = [
6 line.split(",")[0].replace("User:", "").strip()
7 for line in content.splitlines()
8 if "active" in line
9]
10print("Active Users:", active_users)
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
10 lines
Note: Simulating file stream processing using splitlines and list comprehension.
Practice & AssessmentPython Programming Tutorial

Test Your Understanding

Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.

Your Current Score

0 / 0 correct(0 attempted)