Python open() Function

Short answer
open(file, mode='r', encoding=None) opens a file and returns a file object you can read from or write to; use it in a with block so the file is closed automatically.

Every program that saves notes, reads a log or loads a data file starts with open(). It connects your code to a file on disk and gives back a file object with methods such as read(), readline(), write() and iteration over lines.

The habit to learn first is with open(...) as f:, which closes the file for you even when an error occurs. This page focuses on the function itself; the lesson on file handling and the with statement cover the wider picture.

Quick facts
Syntaxopen(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None)
Parametersfile: path of the file; mode: how to open it; encoding: text encoding such as "utf-8"
ReturnsA file object (text by default, bytes in b mode)
RaisesFileNotFoundError, PermissionError, FileExistsError (mode x)
Time complexityOpening is cheap; reading and writing are O(size of data)

File modes: r, w, a, x and the b and + flags

The mode string says what you intend to do. Default is "r", read text. Pick the mode carefully because "w" erases existing content as soon as the file is opened.

ModeMeaningFile must exist?Existing content
"r"Read text (default)YesKept
"w"Write textNo, it is createdErased
"a"Append text at the endNo, it is createdKept
"x"Create and write; fail if it existsMust not existNot applicable
"r+"Read and writeYesKept
"rb", "wb"Binary reading or writing (bytes)As aboveAs above

Why open() belongs in a with block

A file object holds an operating-system resource, and written data may sit in a buffer until the file is closed. A with block guarantees that close() runs when the block ends, normally or through an exception. Without it you must call close() yourself, and a forgotten call can leave data unwritten.

Python
with open("demo.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
print(f.closed)

After the block, f.closed is True.

Text encoding, binary mode and common errors

In text mode Python converts bytes to str using an encoding. The default depends on the operating system, which can make the same program behave differently on different machines. Passing encoding="utf-8" explicitly keeps results consistent, and is a good habit for any text with accents or symbols. Use binary mode ("rb") for images, PDFs and other non-text files.

Trying to read a file that is not there raises FileNotFoundError. To handle that case gracefully see exceptions. For paths, the pathlib module is a friendlier companion.

Examples you can run

Press Run, then edit the code and run it again.

Write a file, then read it back

First write two lines in "w" mode, then reopen the same file for reading.

Write a file, then read it back
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("buy milk\n")
    f.write("call Asha\n")

with open("notes.txt", "r", encoding="utf-8") as f:
    text = f.read()
print(text.splitlines())
Expected output['buy milk', 'call Asha']

Read a file line by line

Looping over the file object yields one line at a time and is memory friendly for large files.

Read a file line by line
with open("cart.txt", "w", encoding="utf-8") as f:
    f.write("pen\nbook\nlamp\n")

with open("cart.txt", encoding="utf-8") as f:
    for number, line in enumerate(f, start=1):
        print(number, line.strip())
Expected output1 pen
2 book
3 lamp

Append without losing existing lines

Mode "a" adds to the end; "w" would have erased the first line.

Append without losing existing lines
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("start\n")

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("finish\n")

with open("log.txt", encoding="utf-8") as f:
    print(f.read().splitlines())
Expected output['start', 'finish']

Create a file only if it does not exist

Mode "x" protects an existing file from being overwritten.

Create a file only if it does not exist
with open("config.txt", "w", encoding="utf-8") as f:
    f.write("theme=dark\n")

try:
    with open("config.txt", "x", encoding="utf-8") as f:
        f.write("theme=light\n")
except FileExistsError:
    print("config.txt already exists")
Expected outputconfig.txt already exists

Common mistakes

Opening a missing file for reading

✗ Wrong

with open("missing.txt") as f:
    print(f.read())
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'

✓ Right

try:
    with open("missing.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("file not found")

Check the path, create the file first, or catch the error.

Using "w" when you meant to add

✗ Wrong

with open("scores.txt", "w") as f:
    f.write("first\n")
with open("scores.txt", "w") as f:
    f.write("second\n")
No error, but the file now contains only `second`. Opening with `"w"` erased `first`.

✓ Right

with open("scores.txt", "w") as f:
    f.write("first\n")
with open("scores.txt", "a") as f:
    f.write("second\n")
with open("scores.txt") as f:
    print(f.read().splitlines())

Use "a" to append.

Writing a number directly

✗ Wrong

with open("total.txt", "w") as f:
    f.write(42)
TypeError: write() argument must be str, not int

✓ Right

with open("total.txt", "w") as f:
    f.write(str(42))

Convert to text with str() or an f-string.

Reading from a file opened for writing

✗ Wrong

with open("out.txt", "w") as f:
    print(f.read())
io.UnsupportedOperation: not readable

✓ Right

with open("out.txt", "w") as f:
    f.write("data")
with open("out.txt") as f:
    print(f.read())

Open with a mode that allows reading, such as "r" or "r+".

Python open() Function: questions people ask

How do I open and read a file in Python?

Use with open("file.txt", encoding="utf-8") as f: and then call f.read() or loop over f. The with block closes the file for you.

What is the difference between w and a mode in open()?

"w" erases the file's existing content when opening, while "a" keeps it and adds new text at the end. Both create the file if it is missing.

Do I need to close a file after open()?

Yes, but a with block does it automatically. Without with, call f.close() yourself or buffered data might not be written.

Keep learning

Step-by-step lessons:
Python File HandlingPython with StatementPython pathlib

Related:
Python input() FunctionPython print() FunctionPython FileNotFoundError: No such file or directoryPython CSV Files

More in built-in functions:
Python print() FunctionPython len() FunctionPython range() FunctionPython type() FunctionPython int() FunctionPython float() FunctionPython str() FunctionPython input() Function See all →