Python File

Beginner
9 min read
Updated: Nov 2026
3 examples
File objects

Definition and Usage

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.

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.

open() Modes

ModeMeaning
"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.

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.

Text vs Binary, Encoding, and Newlines

AspectText modeBinary mode
Data typestrbytes
Object from open()TextIOWrapperBufferedReader, BufferedWriter, BufferedRandom (FileIO with buffering=0)
read(5) countscharactersbytes
EncodingAlways pass encoding="utf-8"; the default depends on the OS localeNone: bytes are stored as they are
Newlinesnewline=None: "\n" becomes os.linesep on write, and \r\n or \r become "\n" on read. newline="" or "\n" turns translation offNever translated
tell() / seek()Opaque positions; only seek(0), seek(0, 2), or saved tell() valuesByte offsets from the start, current position, or end

Reading Patterns

CodeWhat 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.

Writing, Seeking, and Closing

CodeWhat 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.

Common Mistakes

MistakeDo this instead
Forgetting to close the fileUse with open(...) as f:; it closes the file even when an exception is raised.
Reading after the with blockRaises ValueError: I/O operation on closed file. Keep the code inside the block.
Mixing str and bytesWriting 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 encodingIt 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.

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)

How It Works

  1. Temporary folder. Everything happens inside tempfile.TemporaryDirectory(), so the example leaves no files behind.
  2. Write mode. "w" creates the file and write() stores all three lines in one call.
  3. Iterate the file. A file object yields one line at a time; enumerate(f, start=1) numbers them.
  4. 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'")

How It Works

  1. Exclusive create. "x" makes a new file, and a second "x" on the same path raises FileExistsError.
  2. Append. "a" adds Grace after Ada without touching the existing line.
  3. "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)

How It Works

  1. Text is characters. The text-mode read returns 4 characters: 5, a space, the euro sign, and a newline.
  2. Binary is bytes. The euro sign takes 3 bytes in UTF-8, so the binary read returns 6 bytes.
  3. Decode to convert. Decoding the bytes with UTF-8 gives back exactly the text-mode string.
  4. Fixed newline. newline="\n" keeps the byte count at 6 on Windows too.

Next: Python File Methods by Group

Frequently Asked Questions

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.

Browse every file method

Open the method index for categorized guides with examples and FAQs.

File Methods Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful