Learn What open() is in Python: Absolute Beginners Tutorial

Final Exam & Certification

Complete this tutorial and pass the 10-question final exam to earn a downloadable certificate of completion.

skip to exam

Every Python program that touches a file — reading a config, saving output, loading data — starts with one call: open(). This tutorial explains exactly what that function is, what it returns, and how to use it safely from your very first line.

What's in this Python Tutorial

When you write a Python script, everything you work with lives in memory. The moment your program stops, that memory is gone. Files let you store information that outlasts your program — logs, data, results, configuration. The open() function is how Python connects your code to those files.

What open() Is and What It Does

open() is a Python built-in function. That means it comes with Python itself — you never need to import it. When you call it, Python creates a connection to a file on your computer and hands you back a file object. You use that file object to read from or write to the file.

Think of open() like opening a book. The book still exists on the shelf whether you open it or not. When you open it, you get access to its contents and you can start reading. When you are done, you close the book so others can use it. Python files work the same way.

Note

open() does not read the file for you. It opens a connection and gives you an object with methods — like read() or write() — that you then call yourself. Two separate actions: open the connection, then use it.

The Syntax of open()

The official signature from the Python documentation is:

python
open(file, mode='r', buffering=-1, encoding=None,
     errors=None, newline=None, closefd=True, opener=None)

As a beginner, you only need to think about two parameters to start:

open() — Key Parameters
What it controls
The path to the file you want to open. Can be a filename like "notes.txt" (relative to the current working directory) or a full absolute path.
Example
"notes.txt" or "/home/user/data/notes.txt"
What it controls
Controls whether Python opens the file for reading, writing, appending, or binary access. Defaults to "r" if omitted.
Example
"r", "w", "a", "rb"
What it controls
Tells Python how to decode bytes into characters (text mode) or encode characters into bytes (write mode). Optional, but always recommended. Without it, Python uses the OS default, which varies across platforms.
Example
encoding="utf-8"

The simplest possible call looks like this:

python
f = open("notes.txt")   # Opens notes.txt in read mode ('r') by default

Because mode defaults to 'r', you do not have to pass it when reading. The variable f now holds a file object. You will use f to call methods like f.read().

Pro Tip

Always specify encoding="utf-8" for text files. Without it, Python uses the system default encoding, which varies between operating systems and can cause unexpected errors when files contain non-ASCII characters.

File Modes

The mode parameter tells Python what you intend to do with the file. Choosing the wrong mode is one of the most common beginner mistakes — particularly using 'w' when you meant 'a', which silently erases your data.

File Modes — Click a mode to see details
File must exist?
Yes — raises FileNotFoundError if not found.
Creates file?
No.
Erases content?
No. Opens for reading only.
Note
This is the default. You can omit the mode when reading: open("file.txt").
File must exist?
No.
Creates file?
Yes — creates a new file if none exists.
Erases content?
Yes — truncates the file to zero bytes the moment it is opened, before you write anything.
Note
Use with care on existing files. If you want to preserve existing data, use 'a' instead.
File must exist?
No.
Creates file?
Yes — creates a new file if none exists.
Erases content?
No. The write cursor is always positioned at the end of the file.
Note
The correct choice for log files and any situation where you need to accumulate data over multiple writes.
File must exist?
No — and it must not exist. Raises FileExistsError if it does.
Creates file?
Yes — this is its only purpose.
Erases content?
N/A — only used for creating brand-new files.
Note
Safer than 'w' when creating a new file, because it prevents accidentally overwriting an existing one.
File must exist?
Yes — raises FileNotFoundError if not found.
Creates file?
No.
Erases content?
No — opens without truncating. The cursor starts at the beginning.
Note
Allows both reading and writing. Writing at the start of a file overwrites existing bytes in place rather than inserting them.
Used as
A suffix combined with another mode: 'rb', 'wb', 'ab'.
What it does
Disables text encoding/decoding. File contents are returned as bytes objects instead of strings. No newline translation occurs.
When to use
Images, PDFs, audio files, executables, and any non-text file. Using text mode on binary files corrupts the data.
Warning

Opening a file with 'w' erases all existing content immediately on opening, before you write a single character. If you only want to add to a file without touching its existing data, use 'a' instead.

Modes can be combined. For example, 'rb' means read in binary mode, and 'wb' means write in binary mode. Binary mode is used for images, PDFs, executables, and any file that is not plain text.

Reading a File

Once a file is open in read mode, there are three main methods for accessing its contents:

python
with open("notes.txt", "r", encoding="utf-8") as f:
    # 1. read() — returns the entire file as one string
    contents = f.read()
    print(contents)

with open("notes.txt", "r", encoding="utf-8") as f:
    # 2. readline() — returns one line per call; call it again for the next line
    first_line = f.readline()
    second_line = f.readline()

with open("notes.txt", "r", encoding="utf-8") as f:
    # 3. readlines() — returns a list; each element is one line
    lines = f.readlines()
    print(lines)

You can also iterate over a file object directly in a loop, which is memory-efficient for large files because Python reads one line at a time rather than loading everything at once:

python
with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())   # .strip() removes the trailing newline
Code Builder click tokens to build the expression

Build the correct call to open a file named data.txt for reading with UTF-8 encoding, assigning the file object to f.

click tokens below to place them here
encoding="utf-8" open( "w" f , = "data.txt" "r" ) ,
Correct answer: f = open("data.txt", "r", encoding="utf-8") — The file path comes first, then the mode, then the encoding keyword argument. The distractor "w" is the write mode, which would create or overwrite the file rather than read it.

Writing and Appending to a File

Writing to a file uses the write() method on the file object. The key difference between write mode and append mode is what happens to any content already in the file:

python
# Write mode — creates or overwrites the file
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("First entry\n")
    f.write("Second entry\n")

# Append mode — adds to the end without erasing
with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Third entry\n")

Note that write() does not automatically add a newline character at the end of each string. You have to include \n yourself wherever you want a line break.

The writelines() method accepts a list of strings and writes them all in one call, but like write(), it does not insert newlines between items:

python
lines = ["line one\n", "line two\n", "line three\n"]

with open("output.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)
Spot the Bug click the line that contains the error

One of these lines will cause existing file contents to be silently erased when the intention is only to add new data. Click the line responsible.

1 existing_log = "server.log"
2 new_entry = "ERROR: connection timeout\n"
3 with open(existing_log, "w", encoding="utf-8") as f:
4 f.write(new_entry)
Line 3 is the bug. Opening an existing log file with "w" truncates (erases) all its current content the moment the file is opened. The correct mode for adding to a log without destroying history is "a" (append).

The with Statement and Context Managers

Every file you open must eventually be closed. Closing a file releases the system resource (the file handle) it holds. If you forget to close a file, your program ties up that resource until the operating system forcibly reclaims it — or until your script ends.

You can close a file manually by calling f.close(), but this approach has a flaw: if an exception occurs between open() and f.close(), the close never runs:

python
# Fragile — if anything between open and close raises an exception,
# f.close() never runs
f = open("data.txt", encoding="utf-8")
contents = f.read()
f.close()   # May be skipped if an error occurs above

The correct approach is to use the with statement. It creates a context manager that guarantees the file will be closed when the block exits — no matter what:

python
# Correct — file is automatically closed when the block ends
with open("data.txt", encoding="utf-8") as f:
    contents = f.read()
    print(contents)
# f is now closed, even if read() raised an exception

You can open multiple files in a single with statement by separating them with a comma:

python
with open("input.txt", encoding="utf-8") as src, \
     open("output.txt", "w", encoding="utf-8") as dst:
    for line in src:
        dst.write(line.upper())

Handling Errors

When you open a file in read mode and the file does not exist, Python raises a FileNotFoundError. Rather than letting your program crash, you can catch that exception and handle it gracefully:

python
try:
    with open("config.txt", encoding="utf-8") as f:
        data = f.read()
except FileNotFoundError:
    print("config.txt was not found. Using default settings.")
except PermissionError:
    print("Access denied. Check file permissions.")

Two errors are particularly common when working with files: FileNotFoundError (file does not exist when reading) and PermissionError (the operating system blocked access). Catching both gives your program a sensible fallback for the most frequent failure modes.

Check Your Understanding question 1 of 4

How to Open and Read a File in Python

  1. Choose your file path

    Decide whether you are using a relative path (relative to where your script runs) or an absolute path. For beginners, placing the file in the same folder as your script and using just the filename is the simplest starting point. For example, "notes.txt" assumes the file is in the same directory as your script.

  2. Select the correct mode

    Pick 'r' to read an existing file, 'w' to create or overwrite a file, or 'a' to append to an existing file. If the file does not exist and you use 'r', Python will raise a FileNotFoundError.

  3. Open the file with a context manager

    Use the with open(path, mode, encoding="utf-8") as f: syntax. This ensures the file is automatically closed when the block exits, even if an error occurs inside the block.

  4. Read or write the file contents

    Inside the with block, call f.read() to get the full contents as a string, f.readline() to get one line at a time, or f.readlines() to get a list of all lines. For writing, use f.write(text). Remember to include \n manually where you want line breaks.

  5. Handle exceptions

    Wrap your open() call in a try/except block to catch FileNotFoundError when reading a file that may not exist, or PermissionError when the OS denies access. This keeps your program from crashing on predictable failures.

PYTHON LEARNING SUMMARY POINTS

  • open() is a built-in function that opens a file and returns a file object.
  • The default mode is 'r' (read text). You only need to pass a mode when you are doing something other than reading.
  • 'w' creates or overwrites. 'a' appends without erasing. 'x' creates a new file and fails if one already exists.
  • Add 'b' to any mode for binary files: 'rb', 'wb'.
  • Always use with open(...) as f: — it closes the file automatically, even when exceptions occur.
  • Always pass encoding="utf-8" for text files to avoid platform-specific encoding surprises.
  • f.read() returns the whole file as a string. f.readline() returns one line. f.readlines() returns a list of lines.
  • Catch FileNotFoundError and PermissionError to handle the most common file operation failures.

Frequently Asked Questions

open() is a built-in Python function that opens a file and returns a file object you can use to read from or write to that file. It accepts the file path and an optional mode string that controls how the file is accessed. The function itself does not read or write anything — it only establishes the connection.

The default mode is 'r', which opens the file for reading as text. If the file does not exist, Python raises a FileNotFoundError. Because 'r' is the default, you do not need to pass it explicitly when you only want to read.

'w' opens a file for writing and erases all existing content the moment the file is opened. 'a' opens for writing but keeps existing content intact, appending new data to the end of the file. Both modes will create the file if it does not already exist.

The with statement creates a context manager that automatically closes the file when the indented block finishes, even if an exception occurs. Without it, you must call file.close() manually, and forgetting to do so — or having an error prevent that call from running — can cause resource leaks where open file handles accumulate in memory.

Python will truncate (empty) the existing file immediately on opening it in 'w' mode. All previous content is erased before you write anything new. Use 'a' mode if you want to preserve existing content and only add to it.

Adding 'b' to the mode string (for example 'rb' or 'wb') opens the file in binary mode. The file contents are returned as bytes objects instead of strings, with no text encoding or decoding applied. Binary mode is necessary for images, PDFs, executables, and any file that is not plain text.

FileNotFoundError is the exception Python raises when you call open() in read mode ('r') and the specified file path does not exist. It can be caught with a try/except block to handle the missing file gracefully instead of letting the program crash.

read() returns the entire file contents as a single string. readline() returns one line at a time each time it is called, moving the internal cursor forward. readlines() returns a list where each element is one line of the file including its newline character. For large files, iterating over the file object directly (for line in f:) is more memory-efficient than readlines().

Certificate of Completion
Final Exam
Pass mark: 80% · Score 80% or higher to receive your certificate

Enter your name as you want it to appear on your certificate, then start the exam. Your name is used only to generate your certificate and is never transmitted or stored anywhere.

Question 1 of 10