In Python, open(path, mode) opens a file and returns a file object with methods like read(), write(), and line-by-line iteration. The mode says what you want: "r" read (default), "w" write (replacing the file), "a" append, plus "b" for bytes instead of text.
Always open files in a with statement so they are closed automatically, even if an error happens. For text, pass encoding="utf-8" explicitly; otherwise Python uses a platform-dependent default. The examples write into a folder from the tempfile module, so they never touch your real files.
open() is a built-in function: it lives in the builtins module, so it is always available without an import.
Syntax
Use it in a with block.
python
with open(path, "r", encoding="utf-8") as f:
text = f.read()
with open(path, "w", encoding="utf-8") as f:
f.write("hello\n")
Call
What it does
open(p, encoding="utf-8")
Read text (mode "r").
open(p, "w", encoding="utf-8")
Write text, replacing the file.
open(p, "a", encoding="utf-8")
Append text to the end.
open(p, "rb")
Read raw bytes.
Binary modes ("rb", "wb") read and write bytes and take no encoding.
Required. A path (str or pathlib.Path) or a file descriptor.
mode
Optional. "r", "w", "a", "x", with "b" or "t" and "+". Default "r".
encoding
Optional. Text encoding; pass "utf-8" for portable results.
newline
Optional. Controls line-ending translation in text mode.
Return Value
Return Value
Description
file object
A text or binary file object, usable as a context manager.
Python Examples
Example 1 — Write a Text File, Then Read It Back
Create a file in a temporary folder with explicit UTF-8 encoding and read its contents.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "notes.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("first line\n")
f.write("second line\n")
with open(path, encoding="utf-8") as f:
text = f.read()
print(repr(text))
print(os.path.basename(path))
Output
'first line\nsecond line\n'
notes.txt
How It Works
Safe location.TemporaryDirectory() creates a throwaway folder and deletes it at the end.
Write mode."w" creates the file; write() does not add newlines for you.
Read everything.read() returns the whole file as one string; repr() makes the newlines visible.
No absolute path printed.basename() shows only the file name, which is the same on every machine.
Example 2 — Append to a File and Read It Line by Line
Write with print(file=...), append more lines, and number them while reading.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "log.txt")
with open(path, "w", encoding="utf-8") as f:
print("start", file=f)
with open(path, "a", encoding="utf-8") as f:
f.write("step 1\nstep 2\n")
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, 1):
print(number, line.rstrip("\n"))
Output
1 start
2 step 1
3 step 2
How It Works
print to a file.file=f sends the line, with its newline, into the file.
Append mode."a" keeps the existing content and adds to the end.
Iterate lines. Looping over a file object yields one line at a time, which is memory friendly.
Strip the newline. Each line ends with "\n"; rstrip("\n") removes it before printing.
Example 3 — Binary Mode, Missing Files, and Closing
Write and read raw bytes, handle a missing file, and confirm that with closes the file.
python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "data.bin")
with open(path, "wb") as f:
f.write(bytes([0, 255, 65]))
with open(path, "rb") as f:
print(f.read())
try:
open(os.path.join(folder, "missing.txt"), encoding="utf-8")
except FileNotFoundError:
print("missing.txt does not exist")
with open(path, "rb") as f:
print(f.closed)
print(f.closed)
Output
b'\x00\xffA'
missing.txt does not exist
False
True
How It Works
Bytes in, bytes out. Binary mode writes and reads bytes unchanged; 65 shows as the letter A.
No encoding in binary mode. Only text mode takes encoding.
Missing file. Opening a file that does not exist for reading raises FileNotFoundError.
Closed automatically. Inside with the file is open; right after the block it is closed.
Frequently Asked Questions
with open(path, encoding="utf-8") as f: text = f.read(). Loop over f to read line by line.
It closes the file automatically when the block ends, even if an exception occurs.
The default encoding depends on the operating system. Being explicit makes the same file read the same way everywhere.
"w" replaces the file's contents; "a" adds to the end.
Open it with "rb". read() then returns bytes instead of str.