diff -r ed091424f230 Doc/library/functions.rst --- a/Doc/library/functions.rst Sat Nov 03 17:51:25 2012 +0200 +++ b/Doc/library/functions.rst Sat Nov 03 16:15:24 2012 -0400 @@ -934,6 +934,36 @@ (*file*, *flags*). *opener* must return an open file descriptor (passing :mod:`os.open` as *opener* results in functionality similar to passing ``None``). + + The following example is an alternative implementation for opening files + for exclusive writing. Instead of passing ``'x'`` as the *mode*, we + create an open_exclusive function and use it as the *opener*:: + + >>> import os + >>> def open_exclusive(path, mode): + ... return os.open(path, mode | os.O_CREAT | os.O_EXCL) + ... + >>> filename = "/tmp/somefile" + >>> fp = open(filename, 'w', opener=open_exclusive) + >>> fp2 = open(filename, 'w', opener=open_exclusive) + Traceback (most recent call last): + File "", line 1, in + File "", line 1, in + FileExistsError: [Errno 17] File exists: '/tmp/somefile' + + This other example uses the ``dir_fd`` parameter of the :mod:`os.open` + function to open a file relative to a given directory:: + + >>> import os + >>> def open_at(dirname): + ... dir_fd = os.open(dirname, os.O_RDONLY) + ... def opener(path, flags): + ... return os.open(path, flags, dir_fd=dir_fd) + ... return opener + ... + >>> with open("testfile", "w", opener=open_at("/tmp/somedir")) as f: + ... f.write("This will be written in the /tmp/somedir/testfile file.") + ... .. versionchanged:: 3.3 The *opener* parameter was added. diff -r ed091424f230 Doc/library/io.rst --- a/Doc/library/io.rst Sat Nov 03 17:51:25 2012 +0200 +++ b/Doc/library/io.rst Sat Nov 03 16:15:24 2012 -0400 @@ -498,6 +498,9 @@ :mod:`os.open` as *opener* results in functionality similar to passing ``None``). + See the :meth:`open()` built-in function for examples on using the *opener* + parameter. + .. versionchanged:: 3.3 The *opener* parameter was added. The ``'x'`` mode was added.