Python Glossary Русский

Python 3.5+pathlibfunction

.read_text()

reading/writing

Read the whole file into a string and close it — no open() needed; pass `encoding='utf-8'` explicitly.

Syntax

p.read_text(encoding='utf-8')

Before Python 3.15, with no encoding argument Python falls back to the OS locale encoding (UTF-8 since 3.15, PEP 686) — on Windows that is typically cp1251 or cp1252, so a UTF-8 file comes back as mojibake or blows up with UnicodeDecodeError. The entire file is pulled into memory at once, so for multi-gigabyte logs open the file and iterate over lines instead.

Examples

from pathlib import Path
p = Path('test_pathlib.txt')
p.write_text('hello world', encoding='utf-8')
p.read_text() # → 'hello world'
len(p.read_text().splitlines()) # → 1

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy