Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

File I/O | Python Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Python Fundamentals

Lesson 19 of 55

·Python

File I/O

20 minutes

Course progress35%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • Use `open(filename, mode)`; common modes: `'r'`, `'w'`, `'a'`, `'b'`.
  • `with` ensures automatic file closure.
  • `read()`, `readline()`, `readlines()`, or iteration over the file object to read data.
  • `write()` and `writelines()` for output.

File I/O

Reading from and writing to files is straightforward with Python’s built‑in open() function, especially when used inside a with context manager.

# Write to a file
with open('example.txt', 'w') as f:
    f.write('First line
Second line')

# Read the whole file
with open('example.txt', 'r') as f:
    content = f.read()
    print(content)

The with block guarantees that the file is properly closed, even if an error occurs inside the block.

Make it stickPractice what you've learned1 quiz · 5 practical tests · Optional activities from Python FundamentalsBrowse activities
Previous lessonString ManipulationContinue to lesson 20Exception HandlingBack to Python Fundamentals curriculum