Python Glossary Русский

all Python 3osfunction

os.open()

os — file descriptors

Low-level file opening: returns an integer file descriptor according to O_* flags. It is not the built-in open() and not a file object.

Syntax

fd = os.open(path, flags, mode=0o777, *, dir_fd=None)

The result is a number with no read()/write(): you use os.read/os.write with bytes and close it with os.close(fd), and with is not supported, so a forgotten descriptor leaks. Flags are combined with |, as in O_WRONLY|O_CREAT|O_TRUNC, and without O_CREAT a missing file raises FileNotFoundError. Its value lies in what open() lacks: O_CREAT|O_EXCL atomically creates the file or raises FileExistsError, and mode sets the new file's permissions (minus the umask). To get a normal file object wrap the descriptor with os.fdopen(fd); on Windows add O_BINARY for binary data.

Examples

import os
fd = os.open('data.bin', os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o644)
print(type(fd).__name__)  # → int
print(os.write(fd, b'hello'))  # → 5
os.close(fd)
with os.fdopen(os.open('data.bin', os.O_RDONLY), 'rb') as f:
    print(f.read())  # → b'hello'
import os
flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
os.close(os.open('lock', flags))
try:
    os.open('lock', flags)
except FileExistsError:
    print('уже занят')  # → уже занят

See also

Open in the full glossarydocs.python.orgReport an inaccuracy