Python Glossary Русский

all Python 3Files & I/Ofunction

open()

opening

Opens a file. Modes: r (read), w (write, truncating), a (append), x (create), b (binary). Use it with with.

Syntax

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Always pass encoding='utf-8' explicitly: without it, before Python 3.15, text mode falls back to the system locale (utf-8 only in UTF-8 Mode, -X utf8; since 3.15 that mode is on by default, PEP 686), so a file that reads fine on Linux blows up with UnicodeDecodeError on a Windows machine using cp1251. Mode 'w' empties the file the moment it is opened, before any write happens — if you want to create a file without clobbering an existing one, use 'x', which raises FileExistsError instead of destroying data.

Examples

# Запись и чтение текстового файла
with open('demo.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!')
with open('demo.txt', 'r', encoding='utf-8') as f:
    print(f.read())  # → Hello, World!
# Добавление к файлу: режим 'a' пишет в конец
with open('demo.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, World!')
with open('demo.txt', 'a', encoding='utf-8') as f:
    f.write('\nSecond line')
with open('demo.txt', encoding='utf-8') as f:
    print([line.strip() for line in f])  # → ['Hello, World!', 'Second line']
# Бинарный режим
with open('demo.bin', 'wb') as f:
    f.write(bytes([0, 1, 2, 3]))
with open('demo.bin', 'rb') as f:
    print(f.read())  # → b'\x00\x01\x02\x03'
# Режим 'x' — только создать: если файл уже есть, FileExistsError
with open('new.txt', 'x', encoding='utf-8') as f:
    f.write('new')
try:
    open('new.txt', 'x')
except FileExistsError:
    print('файл уже есть')  # → файл уже есть
# encoding='utf-8' обязателен для портируемости: без него кодировка
# берётся из локали ОС, и файл с другой машины прочитается иначе
from pathlib import Path
path = Path('demo.txt')
path.write_text('Привет', encoding='utf-8')
with path.open('r', encoding='utf-8') as f:
    print(f.readline())  # → Привет

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy