Python open() Function Explained
open() is the built-in Python function used to open a file so your program can read from it or write to it.
This page is a beginner-friendly reference for open(). You will learn what it does, the most common arguments, what it returns, and how to use it safely when working with files.
Quick example
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Use with so the file closes automatically. "r" means read mode.
What open() does
open() opens a file and gives your program a way to work with it.
Important points:
- It opens a file so your code can read from it or write to it
- It does not read or write anything by itself
- It returns a file object
- You use methods on that file object, such as:
read()readline()readlines()write()close()
Example:
file = open("example.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()
This works, but in most cases you should use with instead, because it closes the file for you automatically.
Basic syntax
A common form is:
open(file, mode, encoding="utf-8")
Here is what each part means:
fileis the file name or file pathmodecontrols how the file is openedencodingmatters when you are working with text files
Example:
with open("notes.txt", "r", encoding="utf-8") as file:
text = file.read()
print(text)
In this example:
"notes.txt"is the file name"r"means open for readingencoding="utf-8"tells Python how to decode the text
Common file modes
These are the modes beginners use most often:
"r"= read a text file"w"= write a text file and replace existing content"a"= append text to the end of a file"x"= create a new file and fail if it already exists"rb"= read a binary file"wb"= write a binary file
Examples:
# Read a text file
with open("data.txt", "r", encoding="utf-8") as file:
print(file.read())
# Write a text file (overwrites old content)
with open("data.txt", "w", encoding="utf-8") as file:
file.write("Hello\n")
# Append to a text file
with open("data.txt", "a", encoding="utf-8") as file:
file.write("Another line\n")
Be careful with "w" mode. If the file already exists, its old contents are removed.
What open() returns
open() returns a file object.
A file object is the thing you actually use to work with the file. It gives you methods like:
file.read()file.write()file.close()
It also keeps track of the current position in the file.
Example:
with open("example.txt", "r", encoding="utf-8") as file:
print(type(file))
Possible output:
<class '_io.TextIOWrapper'>
You do not need to memorize that type name. The important idea is that open() gives you an object that knows how to interact with the file.
Why beginners should use with
Beginners should usually write file code like this:
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Why this is recommended:
withautomatically closes the file when the block ends- It is safer than calling
close()yourself - It helps prevent bugs caused by leaving files open
- It is the standard pattern you will see in most Python code
Without with, you must remember to close the file yourself:
file = open("example.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()
That version is easier to get wrong.
Reading text with open()
Use mode "r" when you want to read a text file.
Read the whole file
read() returns the full contents as one string.
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Read one line
readline() reads one line at a time.
with open("example.txt", "r", encoding="utf-8") as file:
first_line = file.readline()
print(first_line)
Loop over the file line by line
This is often the best choice for larger files.
with open("example.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
If you want a full beginner walkthrough, see How to Read a File in Python or How to Read a File Line by Line in Python.
Writing text with open()
Use "w" to create a file or overwrite an existing file.
with open("output.txt", "w", encoding="utf-8") as file:
file.write("First line\n")
file.write("Second line\n")
Use "a" if you want to add content without deleting what is already there.
with open("output.txt", "a", encoding="utf-8") as file:
file.write("Third line\n")
Important detail:
write()writes a stringwrite()does not add a newline for you- If you want a new line, include
\nyourself
If your goal is a full task rather than a function reference, see How to Write to a File in Python or How to Append to a File in Python.
Important arguments beginners should know
A few arguments matter more than others when starting out.
encoding="utf-8"
For text files, this is a good default.
with open("message.txt", "r", encoding="utf-8") as file:
print(file.read())
Why it matters:
- It helps Python read text correctly
- It avoids some text decoding problems
- It makes your code more consistent across systems
newline
This is mostly useful when writing CSV files or when you need exact control over line endings.
Beginners usually do not need it for normal text files.
buffering
This is an advanced argument.
Most beginners can ignore it and use the default.
Common errors when using open()
Here are some common file-related errors you may see.
FileNotFoundError
This happens when:
- the file does not exist
- the path is wrong
- your program is running from a different folder than you expect
Example:
with open("missing.txt", "r", encoding="utf-8") as file:
print(file.read())
If you are stuck, see FileNotFoundError: Errno 2 No such file or directory and Working with File Paths in Python.
PermissionError
This happens when Python does not have permission to access the file.
Example causes:
- the file is protected
- you are trying to write somewhere you should not
- another program is blocking access
Related page: PermissionError: Errno 13 Permission denied
IsADirectoryError
This happens when you pass a folder path instead of a file path.
Example:
with open("my_folder", "r", encoding="utf-8") as file:
print(file.read())
Related page: IsADirectoryError: Errno 21 Is a directory
UnicodeDecodeError
This can happen when the file's real encoding does not match the encoding you used in open().
Related page: UnicodeDecodeError: 'utf-8' codec can't decode byte
When to use other pages
This page is a reference for the open() function.
Use other pages when you need something more specific:
- Use a how-to page for a full task, such as reading a file line by line
- Use an error page when you already have a specific exception to fix
- Use a path page when the real problem is the file location, not
open()itself - For a broader introduction, see Python File Handling Basics: Read and Write
Common mistakes
These are some of the most common beginner mistakes with open():
- Using
"r"mode on a file that does not exist - Forgetting to use
encodingfor text files - Using
"w"and accidentally deleting old content - Trying to read from a file opened in write mode
- Passing a folder path instead of a file path
- Using a relative path from the wrong working directory
If you are not sure what Python is trying to open, these quick checks can help:
import os
print(os.getcwd())
This shows the current working directory.
import os
print(os.path.exists("example.txt"))
This checks whether the path exists.
import os
print(os.path.isfile("example.txt"))
This checks whether the path is a file.
with open("example.txt", "r", encoding="utf-8") as file:
print(file.read())
This is a simple test to confirm the file can be opened and read.
FAQ
What does open() return in Python?
It returns a file object. You use that object to read, write, or close the file.
What is the safest way to use open()?
Use it inside a with block so the file closes automatically.
What is the difference between "w" and "a" mode?
"w" overwrites the file. "a" adds new content to the end.
Why do I get FileNotFoundError with open()?
Usually the file path is wrong, the file does not exist, or your program is running from a different folder than you expect.
Should I always set encoding when opening a text file?
It is a good habit. encoding="utf-8" is a safe default for many text files.
See also
- How to Read a File in Python
- How to Write to a File in Python
- How to Append to a File in Python
- How to Read a File Line by Line in Python
- Python File Handling Basics: Read and Write
- Working with File Paths in Python
- FileNotFoundError: Errno 2 No such file or directory
- PermissionError: Errno 13 Permission denied