Opening file in append mode and seeking to start

前端 未结 1 1640
名媛妹妹
名媛妹妹 2021-01-05 02:02

I\'ve come across this strange behavior regarding opening a file in append mode and then attempting to seek to the start of the file.

The code should be self-explana

相关标签:
1条回答
  • 2021-01-05 02:17

    The behaviour is one enforced by your OS.

    The Python 2 open() call is actually opening files the same way your C code does, with a little more wrapping. Both ask the OS to open the file in a given mode. Your OS then explicitly limits where you can seek to; you are not allowed to seek to read or overwrite data that was there before you opened the file.

    In Python 3 I/O has been overhauled and the new file handling code does not directly pass on the mode to the OS, allowing you to not be bound by that restriction. You can do the same in Python 2 by using the io.open() function.

    The open() function documentation certainly warns you about certain OS behaviour where you cannot even use seek when using a:

    [...] 'a' for appending (which on some Unix systems means that all writes append to the end of the file regardless of the current seek position).

    On Linux the open() man page is explicit about just that behaviour:

    O_APPEND
    The file is opened in append mode. Before each write(2), the file offset is positioned at the end of the file, as if with lseek(2).

    e.g. when trying to write, the file position is moved to the end of the file; you are only ever allowed to append.

    I'm looking to find you a list of OSes that behave in that way; it looks like Microsoft Windows does something similar. The .NET FileMode enumeration documentation states:

    Append
    [...] Trying to seek to a position before the end of the file throws an IOException exception, and any attempt to read fails and throws a NotSupportedException exception.

    In any case, if you want to both write to and read from a file (not just append), but not truncate the file when opening, use the 'r+' mode. This opens the file for both reading and writing. You can append by seeking to the end, but at the same time you are free to seek to any point in the file.

    0 讨论(0)
提交回复
热议问题