Python write function
last modified November 29, 2026 Python 3.15
In this article we show how to use the write method to put text or bytes into a file. We look at the value it returns, the missing newline, append mode, binary data, wrong argument types, and the moment the data becomes visible to another handle.
Opening files and choosing a mode is explained in Python open function. Writing an existing iterable of lines in one call is covered in Python writelines function, and closing in Python close function.
The text file
Most examples create the file they write. The report at the end also reads a small file of city names, saved in UTF-8 with one name per line.
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. Opening a file for reading is shown in Python read function.
Writing a string
write takes a string in text mode, appends it at the current position, and returns the number of characters written. It adds no newline and no separator of any kind.
with open('notes.txt', 'w', encoding='utf-8') as f:
print(f.write('milk\n'))
print(f.write('bread\n'))
with open('notes.txt', encoding='utf-8') as f:
print(repr(f.read()))
The two calls return 5 and 6, the lengths of the strings including the newline. The file was opened with 'w', so it was empty at the start, and the second block reads back exactly the two lines.
$ python write_string.py 5 6 'milk\nbread\n'
The return value
In text mode the count is in characters, and in binary mode it is in bytes. For non-ASCII text the two numbers differ.
with open('notes.txt', 'w', encoding='utf-8') as f:
count = f.write('Kraków\n')
print(count)
with open('notes.txt', 'rb') as f:
raw = f.read()
print(len(raw), raw)
Kraków\n is seven characters but eight bytes in UTF-8, which the binary read confirms. On a regular file the whole string is written, so the count is normally the length of the argument; a shorter count would indicate a stream that accepted only part of it.
$ python write_return.py 7 8 b'Krak\xc3\xb3w\n'
No newline is added
Unlike print, write does not append a terminator. Two calls without \n produce one long line.
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('one')
f.write('two')
f.write('\n')
f.write('three\n')
with open('notes.txt', encoding='utf-8') as f:
print(repr(f.read()))
The file contains onetwo\nthree\n: one line made of two writes, then a line with a terminator. Putting \n at the end of the string is the usual way to finish a line.
$ python write_newline.py 'onetwo\nthree\n'
Append mode
The mode decides what happens to existing content. 'w' empties the file, 'a' writes at the end, and 'x' refuses to touch an existing file; Python open function compares all of them.
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('milk\n')
with open('notes.txt', 'a', encoding='utf-8') as f:
print(f.write('bread\n'))
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('eggs\n')
with open('notes.txt', encoding='utf-8') as f:
print(f.read(), end='')
The append call returns 6 and adds bread after milk. The next block opens the file with 'w' again and discards both lines, so only eggs remains. Use 'a' for logs and 'w' when the file is rebuilt from scratch.
$ python write_append.py 6 eggs
Binary mode
In binary mode write takes a bytes-like object and returns the number of bytes written. No encoding and no newline translation take place.
with open('raw.bin', 'wb') as f:
print(f.mode)
print(f.write(b'AB\x00\xff'))
print(f.write(b'CD'))
with open('raw.bin', 'rb') as f:
print(f.read())
The mode is wb, the first call stores four bytes, and the second two. The file contains exactly those six bytes, including the null byte and 0xff. A text handle works with characters and would have to encode them first, which is why binary mode owns this job.
$ python write_binary.py wb 4 2 b'AB\x00\xffCD'
Wrong types
A text handle accepts only str, and a binary handle accepts only bytes-like objects. Mixing them raises TypeError before anything is written.
with open('notes.txt', 'w', encoding='utf-8') as f:
try:
f.write(b'milk\n')
except TypeError as e:
print(type(e).__name__, e)
with open('raw.bin', 'wb') as f:
try:
f.write('milk\n')
except TypeError as e:
print(type(e).__name__, e)
The messages name the required type. Nothing was written in either case, because the type is checked before the data reaches the buffer.
$ python write_types.py TypeError write() argument must be str, not bytes TypeError a bytes-like object is required, not 'str'
Buffering and visibility
Python collects writes in a buffer and passes them to the operating system in larger blocks. Until the buffer is flushed or the file is closed, another handle on the same file may see nothing.
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('milk\n')
with open('notes.txt', encoding='utf-8') as g:
print(repr(g.read()))
with open('notes.txt', encoding='utf-8') as g:
print(repr(g.read()))
Inside the block the reader sees an empty file. After the block the with statement has closed the file, and closing flushes the buffer, so the second read returns both lines. Python flush function covers explicit flushing and Python close function covers closing.
$ python write_buffer.py '' 'milk\n'
Writing a report
Because write accepts any string, a whole report can be built in memory and written in one call.
with open('cities.txt', encoding='utf-8') as f:
names = [line.rstrip('\n') for line in f]
with open('report.txt', 'w', encoding='utf-8') as f:
count = f.write('\n'.join(names) + '\n')
print(count)
with open('report.txt', encoding='utf-8') as f:
print(f.read(), end='')
The cities are read line by line, their terminators are removed, and the names are joined with newlines; the final newline completes the last line. The single call returns 43 characters, and the report reads back as the same six lines. For an iterable that is already in lines, Python writelines function is the direct tool.
$ python write_report.py 43 Paris Prague Vienna Kraków Budapest Warsaw
Source
TextIOBase.write – Python documentation
Reading and Writing Files – Python Tutorial
In this article we have written strings and bytes, checked the returned counts, added newlines by hand, appended instead of overwriting, and seen why a second handle may see an empty file until the buffer is flushed. See also Python writelines function, Python read function, Python open function, Python flush function, and Python close function.
Author
List all Python tutorials.