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)
Call
What 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
Parameter
Description
lines
Any iterable of str (text mode) or bytes-like objects (binary mode). It is consumed once, item by item.
Return Value
Return Value
Description
None
Always. 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())
Output
'redgreenblue'
['red', 'green', 'blue']
How It Works
No separators. The first file contains redgreenblue on one line, the most common writelines() surprise.
Fix with a generator.color + "\n" for color in colors adds the newline to each item as it is written.
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="")
Output
None
name,score
Ana,91
Ben,78
Cy,85
How It Works
Header first. A normal write() adds the column names before the data rows.
Rows on the fly. The f-string generator produces one name,score line per dict entry, in insertion order.
Returns None. Unlike write(), writelines() gives back no count.
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))