Python File Handling

Read and write files.

✍️ 3 exercises + code challenge in this lesson

Use open(filename, mode) to work with files. Modes:

  • "r": read (default); error if the file does not exist.
  • "w": write; creates the file or overwrites it.
  • "a": append to the end.
  • "x": create; error if it already exists.

Always use a with block: it closes the file automatically, even if an error occurs.

The browser editor has a small virtual file system, so this example really creates and reads a file.

Key Takeaways: Python File Handling

Mastering Python File Handling helps you write clean and reliable Python code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

Python File Handling Code Example

Python
with open("notes.txt", "w") as f:
    f.write("Line 1: Learn Python\n")
    f.write("Line 2: Build projects\n")

with open("notes.txt", "a") as f:
    f.write("Line 3: Get hired\n")

with open("notes.txt") as f:
    for line in f:
        print(line.strip())

import os
print("Exists?", os.path.exists("notes.txt"))
os.remove("notes.txt")
print("Exists after delete?", os.path.exists("notes.txt"))
Free sign-in required · Google login available

Python File Handling Practice Exercises

Check what you learned in “Python File Handling”.

/ 3 solved
Fill in the blank

Open a file for appending.

with open("log.txt", "") as f:
✓ Correct! Not quite. Try again.
Multiple choice

Why use a with block when opening files?

✓ Correct! Not quite. Try again.
Code challenge

Write "Hello file" to notes.txt, then read it back and print the content.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services