Python file.write() Method

Beginner
6 min read
Updated: Nov 2026
3 examples
file method

Definition

write() stores data at the current position of a file opened for writing. Text files take a str, binary files take bytes-like objects, and the call returns how many characters or bytes it accepted.

It adds nothing extra: no newline, no space. Data first goes into a buffer and reaches the disk on flush(), close(), or when the buffer fills up.

file.write() is a method of the file objects that the built-in open() returns, so no import is needed. It works on text files (TextIOWrapper), binary files (BufferedReader, BufferedWriter, BufferedRandom), and raw files (FileIO, opened with buffering=0).

Syntax

Pass exactly one string or bytes object.

python
count = f.write(text)
count = f.write(data)
CallWhat it does
f.write("hi\n")Text mode: writes three characters and returns 3.
f.write(b"\x00\xff")Binary mode: writes two bytes and returns 2.
f.write(42)Raises TypeError: convert with str(42) first.

Need several values or an automatic newline? print(a, b, file=f) formats them like the screen output and adds "\n".

Method signatures
python
TextIOWrapper.write(s, /)    # -> int, number of characters
BufferedWriter.write(b, /)   # -> int, number of bytes
FileIO.write(b, /)           # -> int, may be less than len(b)

Parameters

ParameterDescription
s / bA str for text files; a bytes-like object (bytes, bytearray, memoryview) for binary files.

Return Value

Return ValueDescription
intText mode: characters written, which is len(s). Binary buffered mode: bytes written, which is len(b).
smaller intOnly a raw FileIO (buffering=0) may write fewer bytes than given; check and retry if you use one.

Python Examples

Each example works inside a temporary folder that is deleted at the end, so nothing is left on your disk.

Example 1 — Count What write() Returns

Add two lines to a shopping list and compare the returned counts with the size on disk.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "shopping.txt")
    with open(path, "w", encoding="utf-8", newline="\n") as f:
        first = f.write("apples 3\n")
        second = f.write("bread 1\n")

    print(first, second, first + second)
    print(os.path.getsize(path), "bytes on disk")

How It Works

  1. Characters, newline included. "apples 3\n" is 9 characters and "bread 1\n" is 8, which is what each call returns.
  2. Fixed line endings. newline="\n" stops Windows from writing \r\n, so the file holds exactly the characters written.
  3. ASCII means 1 byte each. With plain ASCII text, 17 characters become 17 bytes, as os.path.getsize() confirms after the file is closed.

Example 2 — Hit the str vs bytes TypeError on Purpose

Write a score as text, then try the wrong type in both text and binary mode.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "score.txt")
    with open(path, "w", encoding="utf-8") as f:
        try:
            f.write(42)
        except TypeError:
            print("text files need str, not int")
        f.write(str(42) + "\n")
        print("final", 42 * 2, file=f)

    with open(path, "ab") as f:
        try:
            f.write("bonus 5\n")
        except TypeError:
            print("binary files need bytes, not str")
        f.write(b"bonus 5\n")

    with open(path, encoding="utf-8") as f:
        print(f.read().splitlines())

How It Works

  1. No automatic conversion. A text file refuses the integer 42 with TypeError; str() converts it first.
  2. print() to a file. print(..., file=f) formats several values and adds the newline for you.
  3. Binary wants bytes. In "ab" mode a str is rejected; the b"..." literal is accepted and appended at the end.
  4. Three clean lines. Reading back with splitlines() shows every write landed, in order.

Example 3 — Append Runs to a Log, Then Reset It

Add lines with "a" mode, then reopen with "w" and watch the old content disappear.

python
import os
import tempfile


def show(path):
    with open(path, encoding="utf-8") as f:
        print(repr(f.read()))


with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "runs.log")
    with open(path, "w", encoding="utf-8") as f:
        f.write("run 1\n")
    with open(path, "a", encoding="utf-8") as f:
        f.write("run 2\n")
        f.write("run 3\n")
    show(path)

    with open(path, "w", encoding="utf-8") as f:
        f.write("reset\n")
    show(path)

How It Works

  1. Create. The first "w" creates the log with one line.
  2. Append keeps history. "a" positions every write at the end, so runs 2 and 3 follow run 1.
  3. "w" empties first. Reopening with "w" truncates the file to zero bytes before anything is written, so only reset remains.
  4. Helper reader. show() opens its own handle, which only works after the writers above were closed and flushed.

Frequently Asked Questions

The number of characters written for a text file, or bytes written for a binary file. Most code ignores it, but it is handy for counting output.
No. Add "\n" yourself, or use print(value, file=f), which adds a newline automatically.
The file is in text mode and you passed bytes or a number. Convert numbers with str(), or open the file in binary mode for bytes.
Open the file with mode "a". Mode "w" empties an existing file as soon as it is opened.
It is still in the buffer. It reaches the file when you call flush(), close the file, or leave the with block.

Next: file.writelines()

Write every string or bytes object from an iterable, without adding newlines.

writelines() →

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.

11 people found this page helpful