Difference between modes a, a+, w, w+, and r+ in built-in open function?

后端 未结 6 1590
梦毁少年i
梦毁少年i 2020-11-21 05:43

In the python built-in open function, what is the exact difference between the modes w, a, w+, a+, and r+?

6条回答
  •  我在风中等你
    2020-11-21 06:20

    I think this is important to consider for cross-platform execution, i.e. as a CYA. :)

    On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

    This is directly quoted from Python Software Foundation 2.7.x.

提交回复
热议问题