All lessons
πŸ“‚

File Handling

Read and write files

Reward
+50 XP

Opening files

Use open() with a mode: 'r' (read), 'w' (write), 'a' (append). Always close or use with.

# Using 'with' automatically closes the file
with open("example.txt", "w") as f:
    f.write("Hello, file!")

Reading files

Read the entire file, line by line, or into a list.

with open("example.txt", "r") as f:
    content = f.read()
    print(content)

Try it yourself

Run the example below. Edit it and see what changes.

main.py
Output
Press Run to execute (Ctrl/Cmd+Enter)

Common mistakes

  • ⚠Forgetting to close files β€” use 'with' to auto-close.
  • ⚠Opening in 'w' mode erases existing content β€” use 'a' to append.
  • ⚠FileNotFoundError when the file doesn't exist in 'r' mode.