[Tutor] Simultaneous read and write on file

eryk sun eryksun at gmail.com
Mon Jan 18 17:42:52 EST 2016


On Mon, Jan 18, 2016 at 10:01 AM, Anshu Kumar <anshu.kumar726 at gmail.com> wrote:
> I have read in documentation that wb+ mode is for writing and reading. Am i
> using wrong mode, should i use rb+ ?

Use w+ to create a new file, opened with read and write access. Use r+
to open an existing file with read and write access. Unlike w+, r+
does not truncate the file and will not create a new file.

To clarify what Alan said, the "+" modes do not 'lock' the file. On
Windows you may experience a sharing violation if another program
doesn't share write access. This isn't quite the same as a file lock.
All open references to a file have to agree on read, write, and delete
sharing. For example, when Notepad saves a file, it tries to open a
handle that shares only read access. If this open succeeds, Notepad
knows that it's the only writer. (It doesn't care if there are
multiple readers.) On the other hand, if some other program has the
file open with write or delete access, Notepad's open will fail with a
sharing violation. Then it displays a message box saying it can't save
the file because another process has it open, and it offers to save
the file using a different name.

FYI, in terms of POSIX open flags [1], the file mode gets mapped as follows:

      |       flags       |   no +   |   +
    -----------------------------------------
    r |                   | O_RDONLY | O_RDWR
    w | O_CREAT, O_TRUNC  | O_WRONLY | O_RDWR
    a | O_CREAT, O_APPEND | O_WRONLY | O_RDWR

Python 3 only:

    x | O_CREAT, O_EXCL   | O_WRONLY | O_RDWR

In terms of Windows open dispositions and access modes [2], the file
mode gets mapped as follows:

      |  disposition  |      no +     |            +
    ---------------------------------------------------------------
    r | OPEN_EXISTING | GENERIC_READ  | GENERIC_READ, GENERIC_WRITE
    w | CREATE_ALWAYS | GENERIC_WRITE | GENERIC_READ, GENERIC_WRITE
    a | OPEN_ALWAYS   | GENERIC_WRITE | GENERIC_READ, GENERIC_WRITE

Python 3 only:

    x | CREATE_NEW    | GENERIC_WRITE | GENERIC_READ, GENERIC_WRITE

O_APPEND entails an implicit seek to the end of a file before every
write. Note that Python uses the Windows CRT for file access, which
doesn't use the native FILE_APPEND_DATA access to implement O_APPEND.
Instead it opens the file for generic writing and manually updates the
file pointer. This may cause problems if the security descriptor only
allows appending to a file. In this case you'd have to call CreateFile
directly (e.g. via ctypes or win32api).

[1]: http://pubs.opengroup.org/onlinepubs/9699919799/functions/open.html
[2]: https://msdn.microsoft.com/en-us/library/aa363858


More information about the Tutor mailing list