Python file.writelines() Method

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

Definition

writelines() takes an iterable of strings (text mode) or bytes-like objects (binary mode) and writes them one after another, exactly like calling write() on each.

Despite its name it does not add line endings. Each item must already end with "\n" if you want separate lines.

file.writelines() 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 a list, tuple, generator, or any other iterable.

python
f.writelines(lines)
f.writelines(item + "\n" for item in items)
CallWhat it does
f.writelines(["a\n", "b\n"])Writes two lines; returns None.
f.writelines(["a", "b"])Writes ab: no separators are added.
f.writelines(x + "\n" for x in xs)A generator works too; nothing is built in memory first.

"\n".join(items) followed by one write() is an alternative, but remember to add the final newline yourself.

Method signatures
python
IOBase.writelines(lines, /)   # -> None
# text files: every item must be str; binary files: bytes-like

Parameters

ParameterDescription
linesAny iterable of str (text mode) or bytes-like objects (binary mode). It is consumed once, item by item.

Return Value

Return ValueDescription
NoneAlways. Unlike write(), no count is returned.

Python Examples

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

Example 1 — See writelines() Glue Items Together

Write a list of colors as-is, then write it again with a newline added to each item.

python
import os
import tempfile

colors = ["red", "green", "blue"]

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "colors.txt")
    with open(path, "w", encoding="utf-8") as f:
        f.writelines(colors)
    with open(path, encoding="utf-8") as f:
        print(repr(f.read()))

    with open(path, "w", encoding="utf-8") as f:
        f.writelines(color + "\n" for color in colors)
    with open(path, encoding="utf-8") as f:
        print(f.read().splitlines())

How It Works

  1. No separators. The first file contains redgreenblue on one line, the most common writelines() surprise.
  2. Fix with a generator. color + "\n" for color in colors adds the newline to each item as it is written.
  3. Three lines now. splitlines() on the rewritten file returns the three color names again.

Example 2 — Write Score Rows from a Dict

Turn a dict of scores into CSV lines with an f-string generator and check the return value.

python
import os
import tempfile

scores = {"Ana": 91, "Ben": 78, "Cy": 85}

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "scores.csv")
    with open(path, "w", encoding="utf-8") as f:
        f.write("name,score\n")
        result = f.writelines(f"{name},{score}\n" for name, score in scores.items())

    print(result)
    with open(path, encoding="utf-8") as f:
        for line in f:
            print(line, end="")

How It Works

  1. Header first. A normal write() adds the column names before the data rows.
  2. Rows on the fly. The f-string generator produces one name,score line per dict entry, in insertion order.
  3. Returns None. Unlike write(), writelines() gives back no count.
  4. Echo without doubling. end="" stops print() adding a second newline after each stored line.

Example 3 — Join Binary Pieces into One Packet

Write bytes, a bytearray, and a memoryview in one call, and see a str item rejected.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "packet.bin")
    parts = [b"\x00\x01", bytearray(b"\x02"), memoryview(b"\x03\x04")]
    with open(path, "wb") as f:
        f.writelines(parts)
        try:
            f.writelines(["text"])
        except TypeError:
            print("binary writelines() needs bytes-like items")

    with open(path, "rb") as f:
        data = f.read()
    print(list(data), len(data))

How It Works

  1. Mixed bytes-like items. bytes, bytearray, and memoryview objects can all be written to a binary file.
  2. Wrong item type. A str in a binary writelines() raises TypeError; nothing from that call reaches the file.
  3. Byte values. list(data) shows the five stored values 0 to 4, in the order the pieces were listed.

Frequently Asked Questions

No. It writes each item exactly as given. Add "\n" to every item, for example with a generator: f.writelines(x + "\n" for x in items).
Always None. If you need a count, sum the lengths yourself or call write() for each item.
Yes. Any iterable works, and a generator expression avoids building a big list in memory first.
write() takes one string and returns a count. writelines() takes an iterable of strings and returns None. Neither adds newlines.
No. Text files need str items and binary files need bytes-like items, otherwise TypeError is raised. Convert with str() or map(str, numbers) first.

Back to the method index

See all 20 file method guides grouped by what they do.

Method 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