A file object is what the built-in open() returns: a connection to a file on disk with a current position, a mode that says what you may do, and methods such as read(), write(), seek(), and close().
Text files (TextIOWrapper) work with str; binary files (BufferedReader, BufferedWriter, BufferedRandom, or a raw FileIO) work with bytes. The File Methods index lists every method guide.
Syntax
Python Syntax
Open with a mode and an explicit encoding, work inside a with block, and the file closes itself:
Python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "hello.txt")
with open(path, "w", encoding="utf-8") as f: # "w" creates or empties
f.write("Hello\nfile\n")
with open(path, encoding="utf-8") as f: # "r" is the default mode
print(f.read().split()) # ['Hello', 'file']
print(f.closed) # True
Full signature.
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None). Pass encoding for every text file; leave it out for binary modes.
Reference
open() Modes
Mode
Meaning
"r"
Read (the default). The file must exist, otherwise FileNotFoundError.
"w"
Write. Creates the file, or empties an existing one as soon as it opens.
"a"
Append. Creates the file if needed; every write goes to the end.
"x"
Exclusive create. Raises FileExistsError if the file already exists.
"b"
Binary: read and write bytes, as in "rb", "wb", "ab".
"t"
Text (the default): read and write str; "r" means "rt".
"+"
Add the other direction: "r+" updates an existing file, "w+" empties then reads and writes, "a+" appends and reads.
Concept
The with Statement
with open(...) as f: is the recommended pattern. When the block ends, even through an exception, Python calls close(), which flushes buffered writes. Using f afterwards raises ValueError: I/O operation on closed file.
Compare
Text vs Binary, Encoding, and Newlines
Aspect
Text mode
Binary mode
Data type
str
bytes
Object from open()
TextIOWrapper
BufferedReader, BufferedWriter, BufferedRandom (FileIO with buffering=0)
read(5) counts
characters
bytes
Encoding
Always pass encoding="utf-8"; the default depends on the OS locale
None: bytes are stored as they are
Newlines
newline=None: "\n" becomes os.linesep on write, and \r\n or \r become "\n" on read. newline="" or "\n" turns translation off
Never translated
tell() / seek()
Opaque positions; only seek(0), seek(0, 2), or saved tell() values
Byte offsets from the start, current position, or end
Reference
Reading Patterns
Code
What you get
for line in f:
One line at a time, newline included. The best default for text.
f.read()
The rest of the file as one str or bytes object.
f.read(size)
At most size characters or bytes; loop until it returns empty.
f.readline()
Only the next line; "" at the end of the file.
f.readlines()
Every remaining line as a list.
Path(p).read_text(encoding="utf-8")
pathlib shortcut: open, read, and close in one call.
Reference
Writing, Seeking, and Closing
Code
What it does
f.write(s)
Write one string or bytes object and get the count back. No newline is added.
f.writelines(items)
Write every item of an iterable, again without newlines.
print(x, file=f)
Format values like print() and add "\n".
f.seek(pos) / f.tell()
Move to a position or report the current one.
f.flush()
Push buffered data to the operating system; the file stays open.
f.close()
Flush and release the file; with does it for you.
Reference
Common Mistakes
Mistake
Do this instead
Forgetting to close the file
Use with open(...) as f:; it closes the file even when an exception is raised.
Reading after the with block
Raises ValueError: I/O operation on closed file. Keep the code inside the block.
Mixing str and bytes
Writing b"x" to a text file, or "x" to a binary file, raises TypeError.
Opening an existing file with "w"
It is emptied immediately. Use "a" to add, "r+" to update, or "x" to refuse to overwrite.
Relying on the default encoding
It comes from the OS locale (often cp1252 on Windows). Pass encoding="utf-8".
Writing to a file opened with open(path)
The default mode is read-only, so write() raises io.UnsupportedOperation.
Code
Python Examples
Each example works in a temporary folder, so nothing is left behind.
Example 1 — Write a List, Then Loop Over Its Lines
Create a grocery list with "w", then read it back line by line with a numbered loop.
Python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "groceries.txt")
with open(path, "w", encoding="utf-8") as f:
f.write("eggs\nrice\nlemons\n")
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
print(number, line.rstrip("\n"))
print(f.closed)
Output
1 eggs
2 rice
3 lemons
True
How It Works
Temporary folder. Everything happens inside tempfile.TemporaryDirectory(), so the example leaves no files behind.
Write mode."w" creates the file and write() stores all three lines in one call.
Iterate the file. A file object yields one line at a time; enumerate(f, start=1) numbers them.
Closed by with. After the block, f.closed is True without any explicit close().
Example 2 — Compare the x, a, and w Modes
Create a visitor list exclusively, append a name, then see what reopening with "w" does.
Python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "visitors.txt")
with open(path, "x", encoding="utf-8") as f:
f.write("Ada\n")
try:
open(path, "x", encoding="utf-8")
except FileExistsError:
print("'x' refuses to replace an existing file")
with open(path, "a", encoding="utf-8") as f:
f.write("Grace\n")
with open(path, encoding="utf-8") as f:
print(f.read().split())
with open(path, "w", encoding="utf-8") as f:
pass
print(os.path.getsize(path), "bytes after reopening with 'w'")
Output
'x' refuses to replace an existing file
['Ada', 'Grace']
0 bytes after reopening with 'w'
How It Works
Exclusive create."x" makes a new file, and a second "x" on the same path raises FileExistsError.
Append."a" adds Grace after Ada without touching the existing line.
"w" truncates on open. Opening with "w" and writing nothing still empties the file to 0 bytes.
Example 3 — Read the Same File as Text and as Bytes
One line with a euro sign, read once as characters and once as raw UTF-8 bytes.
Python
import os
import tempfile
with tempfile.TemporaryDirectory() as folder:
path = os.path.join(folder, "price.txt")
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write("5 \u20ac\n")
with open(path, encoding="utf-8") as f:
text = f.read()
with open(path, "rb") as f:
data = f.read()
print(len(text), ascii(text))
print(len(data), data)
print(data.decode("utf-8") == text)
Output
4 '5 \u20ac\n'
6 b'5 \xe2\x82\xac\n'
True
How It Works
Text is characters. The text-mode read returns 4 characters: 5, a space, the euro sign, and a newline.
Binary is bytes. The euro sign takes 3 bytes in UTF-8, so the binary read returns 6 bytes.
Decode to convert. Decoding the bytes with UTF-8 gives back exactly the text-mode string.
Fixed newline.newline="\n" keeps the byte count at 6 on Windows too.
Call open(path, mode, encoding="utf-8") inside a with statement: with open("notes.txt", encoding="utf-8") as f:. The mode defaults to "r" for reading text.
Without it, Python uses the operating system locale, which differs between machines (for example cp1252 on many Windows setups). An explicit encoding makes the file read the same everywhere.
"w" empties an existing file as soon as it is opened and writes from the start. "a" keeps the content and adds every write at the end.
For anything that is not text, such as images, archives, or network data, and whenever you need exact byte counts and offsets. Binary mode reads and writes bytes and never changes line endings.
No. The with statement closes the file automatically when the block ends, even if an exception is raised inside it.