Python Glossary Русский

Python 3.5+pathlibfunction

.write_text()

reading/writing

Write a string to the file, overwriting it entirely, and return the number of characters written; the file is closed automatically.

Syntax

p.write_text(data, encoding='utf-8')

The return value counts characters, not bytes, so with Cyrillic or emoji the file on disk is bigger than the number you get back. Writing happens in text mode, so line endings are translated to the platform default and on Windows end up as CRLF — pass the newline argument (added in Python 3.10) when you need the exact bytes you handed in.

Examples

from pathlib import Path
p = Path('test_pathlib.txt')
p.write_text('hello world', encoding='utf-8') # → 11
p.write_text('line1\nline2')
p.read_text().splitlines() # → ['line1', 'line2']

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy