ZetCode

Python writelines function

last modified November 29, 2026 Python 3.15

In this article we show how to use the writelines method to write an iterable of strings in one call. We look at the separators it does not add, the iterables it accepts, its return value, type errors, and a round trip with readlines.

Writing a single string is covered in Python write function, and reading all lines into a list in Python readlines function. Opening files is explained in Python open function.

The text file

Most examples build their own list of names. The round trip and the copy at the end read a small file of city names, saved in UTF-8 with one name per line.

cities.txt
Paris
Prague
Vienna
Kraków
Budapest
Warsaw

The accented ó in Kraków takes two bytes in UTF-8 but counts as a single character, which matters for every method that counts one or the other.

A list of lines

writelines takes an iterable of strings and writes them one after another. The strings must already contain their line terminators.

writelines_list.py
lines = ['Paris\n', 'Prague\n', 'Vienna\n']

with open('names.txt', 'w', encoding='utf-8') as f:
    print(f.writelines(lines))

with open('names.txt', encoding='utf-8') as f:
    print(repr(f.read()))

The method returns None, which is the first line of output. The file contains the three lines exactly as they were in the list, each ending with the newline it carried.

$ python writelines_list.py
None
'Paris\nPrague\nVienna\n'

No separators are added

The name is slightly misleading: writelines writes lines, it does not create them. Without \n the strings are glued together.

writelines_separators.py
with open('names.txt', 'w', encoding='utf-8') as f:
    f.writelines(['Paris', 'Prague', 'Vienna'])

with open('names.txt', encoding='utf-8') as f:
    print(repr(f.read()))

The file holds ParisPragueVienna as one word. Adding separators is the caller's job: put \n into the strings, or join them first, as Python write function shows.

$ python writelines_separators.py
'ParisPragueVienna'

Any iterable works

A list, a tuple, a generator, and a file object are all accepted. The method consumes the iterable from left to right and writes each string as it arrives.

writelines_iterables.py
with open('names.txt', 'w', encoding='utf-8') as f:
    f.writelines(('Paris\n', 'Prague\n'))
    f.writelines(f'{i}: {name}\n' for i, name in enumerate(['Vienna', 'Kraków'], start=3))

with open('names.txt', encoding='utf-8') as f:
    print(f.read(), end='')

The tuple supplies the first two lines and the generator expression the numbered ones. enumerate with start=3 numbers the last two cities 3 and 4, and the generator creates each string only when it is needed, so a long sequence does not have to be held in memory.

$ python writelines_iterables.py
Paris
Prague
3: Vienna
4: Kraków

The return value

writelines returns None, unlike write, which returns the number of characters written.

writelines_return.py
with open('names.txt', 'w', encoding='utf-8') as f:
    print(f.writelines(['Paris\n', 'Prague\n']))
    print(f.write('Vienna\n'))

with open('names.txt', encoding='utf-8') as f:
    print(repr(f.read()))

The first line of output is None; the second is 7, the length of Vienna\n. The file still receives three lines. If the count matters, write the strings one by one with write.

$ python writelines_return.py
None
7
'Paris\nPrague\nVienna\n'

Non-string items

Every item must be a string. An integer or a bytes object raises TypeError, and the items before the bad one have already been written.

writelines_types.py
with open('names.txt', 'w', encoding='utf-8') as f:
    try:
        f.writelines(['Paris\n', 7, 'Vienna\n'])
    except TypeError as e:
        print(type(e).__name__, e)

with open('names.txt', 'w', encoding='utf-8') as f:
    try:
        f.writelines([b'Paris\n'])
    except TypeError as e:
        print(type(e).__name__, e)

The first attempt fails on 7 with the same message that write produces, after Paris\n has already reached the file. The second attempt fails on a bytes item, because a text handle requires str. A file written this way can end up half complete.

$ python writelines_types.py
TypeError write() argument must be str, not int
TypeError write() argument must be str, not bytes

A round trip with readlines

readlines returns a list that keeps the newlines, and writelines can write that list back unchanged.

writelines_roundtrip.py
with open('cities.txt', encoding='utf-8') as f:
    lines = f.readlines()

with open('copy.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)

with open('copy.txt', encoding='utf-8') as f:
    print(f.readlines() == lines)

The copy compares equal to the original list. Both files have the same six lines with the same terminators, so the two methods mirror each other.

$ python writelines_roundtrip.py
True

Copying a file

A file object yields its lines, so writelines can copy a text file without loading all of it into memory at once.

writelines_copy.py
with open('cities.txt', encoding='utf-8') as src, open('copy.txt', 'w', encoding='utf-8') as dst:
    dst.writelines(src)

with open('copy.txt', 'rb') as a, open('cities.txt', 'rb') as b:
    print(a.read() == b.read())

The binary comparison of the two files returns True, so even the bytes match. The source and the destination are opened in the same with statement and both are closed when it ends.

$ python writelines_copy.py
True

Source

IOBase.writelines – Python documentation

Methods of File Objects – Python Tutorial

In this article we have written lists, tuples, generators, and file objects with writelines, seen that it adds nothing between the strings, handled type errors, and copied a file line by line. See also Python write function, Python readlines function, and Python open function.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.