Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Files Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Reading and Writing Files in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How to open, read, and write files
  • The with statement (context manager)
  • File modes (r, w, a, r+)
Terminalpython
# Writing to a file
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line.\n")

# Reading from a file
with open("output.txt", "r") as f:
    content = f.read()       # Read entire file
    print(content)

# Read line by line
with open("output.txt", "r") as f:
    for line in f:
        print(line.strip())   # strip() removes newline

# Append to a file
with open("output.txt", "a") as f:
    f.write("Third line.\n")
Always use with open()
The with statement automatically closes the file when done, even if an error occurs. Never use bare open() without with.

Practical Exercise

Write 3 lines to a file with with open('test.txt', 'w')
Read it back with with open('test.txt', 'r')
Append a 4th line with mode 'a'
Read line by line with for line in f
Use .readlines() to get all lines as a list

Key Takeaways

  • with open(path, mode) as f: - always use this pattern.
  • Modes: r (read), w (write, overwrites), a (append).
  • f.read() = entire file. f.readline() = one line.
  • for line in f: iterates line by line.
  • with auto-closes the file. Never use bare open().
Previously: Module 5 covered OOP.
Today: You learned: Read and write files in Python.
Next: Lesson 38 covers CSV files.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments