Unit 7 • Lesson 2

Opening and Closing Files

Overview

Python's built-in open() function allows you to access files in various modes like read ('r'), write ('w'), and append ('a'). You'll also discover the importance of closing files properly to prevent memory leaks and data loss, ensuring reliable file operations.

Beginner 20–25 min

What You Will Learn in This Lesson

By the end of this lesson, you will know:

  • How to open files: Use Python's open() function to access files.
  • File modes: Understand read ('r'), write ('w'), and append ('a') modes.
  • How to close files: Learn why closing files is important and how to do it.
  • File objects: Understand what open() returns and how to use it.
  • Common mistakes: Avoid forgetting to close files and using wrong modes.

The open() Function

Python's open() function is how you tell Python which file you want to work with. It creates a connection between your program and the file on your computer.

Basic Syntax
file = open("filename.txt", "mode")

Two Required Arguments

  1. Filename: The name (and path) of the file you want to open
  2. Mode: What you want to do with the file (read, write, etc.)
Example: Opening a File
# Open a file called "data.txt" for reading
file = open("data.txt", "r")

# Now you can work with the file
# ... (we'll learn what to do next)

# Always close when done
file.close()

File Modes

When you open a file, you must specify what you want to do with it. This is called the file mode. Python has several modes:

Mode Name What It Does What Happens if File Doesn't Exist
'r' Read Read data from the file Error (FileNotFoundError)
'w' Write Write data to the file (overwrites existing content) Creates a new file
'a' Append Add data to the end of the file Creates a new file
'x' Exclusive Create a new file (fails if file exists) Creates a new file

Default Mode

If you don't specify a mode, Python defaults to 'r' (read mode). However, it's better to always specify the mode explicitly for clarity.

Opening Files in Different Modes

Read Mode ('r')

Use this when you want to read data from an existing file. The file must exist, or you'll get an error.

file = open("data.txt", "r")
# Now you can read from the file
file.close()

Write Mode ('w')

Use this when you want to write data to a file. Warning: This will delete all existing content in the file if it already exists!

file = open("output.txt", "w")
# Now you can write to the file
# This will overwrite any existing content
file.close()

Append Mode ('a')

Use this when you want to add new data to the end of an existing file without deleting what's already there.

file = open("log.txt", "a")
# Now you can add new lines to the end
# Existing content stays intact
file.close()

What Does open() Return?

When you call open(), it returns a file object. This object represents the connection to your file and has methods you can use to read from or write to it.

Understanding File Objects
# open() returns a file object
file = open("data.txt", "r")

# You can check what type it is
print(type(file))  # 

# The file object has methods like read(), write(), close()
# We'll learn about these in the next lessons

file.close()

Think of it like this: The file object is like a handle or a key that gives you access to the file. You use this handle to perform operations on the file.

Why You Must Close Files

Closing files is very important. Here's why:

1

Saves Your Changes

When you write to a file, Python may not immediately save the data to disk. Closing the file ensures all changes are written.

2

Frees Resources

Open files use system resources. Closing them frees up memory and file handles that other programs might need.

3

Prevents Data Loss

If your program crashes or you forget to close a file, you might lose data that hasn't been saved yet.

Always Close Files
# Open a file
file = open("data.txt", "r")

# Do your work with the file
content = file.read()

# Always close when done!
file.close()

Common Mistakes

Mistake 1: Forgetting to Close

# ❌ BAD: File never closed
file = open("data.txt", "r")
content = file.read()
# Oops! Forgot to close

# ✅ GOOD: Always close
file = open("data.txt", "r")
content = file.read()
file.close()  # Don't forget this!

Mistake 2: Wrong Mode

# ❌ BAD: Trying to write in read mode
file = open("data.txt", "r")
file.write("Hello")  # Error! Can't write in read mode

# ✅ GOOD: Use write mode for writing
file = open("data.txt", "w")
file.write("Hello")  # This works!
file.close()

Mistake 3: File Doesn't Exist (Read Mode)

# ❌ BAD: File doesn't exist
file = open("nonexistent.txt", "r")  # FileNotFoundError!

# ✅ GOOD: Check if file exists first, or use write/append mode
# (We'll learn better ways to handle this with try/except later)

Practice: Opening and Closing Files

Try It Yourself

Try opening a file in different modes. Notice how each mode behaves differently:

Click "Run Code" to see your output here

What happened? You opened a file in write mode, wrote some text to it, and then closed it. The file was created (or overwritten if it existed) with your text.

Summary

In this lesson, you learned:

  • open() function: Opens a file and returns a file object
  • File modes: 'r' for reading, 'w' for writing, 'a' for appending
  • Closing files: Always call close() when done to save changes and free resources
  • File objects: The object returned by open() that you use to interact with the file

Remember

Always follow this pattern: Open → Use → Close. Never forget to close your files!

End-of-Lesson Exercises

Think about these questions to reinforce what you've learned:

Exercise 1: File Modes

What's the difference between 'w' mode and 'a' mode? When would you use each?

Exercise 2: Why Close?

Explain why it's important to close files after using them.