Python Glossary Русский

all Python 3Files & I/Ofunction

io.TextIOBase.write()

writing

Write a string to the file and return the number of characters written; it adds no line breaks, so '\n' must be written explicitly.

Syntax

f.write(s)

In text mode write() accepts a string and nothing else: convert numbers or lists with str() or an f-string first, otherwise you get a TypeError; in 'wb' mode it is the opposite and only bytes are allowed. Watch the file mode too — 'w' truncates the file to zero at the moment of open(), even if you never write anything afterwards; to add to the end you need 'a'.

Examples

with open('out.txt', 'w') as f:
    f.write('Hello')
    f.write('\nWorld')
with open('out.txt', 'w') as f:
    n = f.write('Hello World')
print(n)  # → 11

See also

Open in the full glossarydocs.python.orgReport an inaccuracy