File write, weird behaviour
Mats Wichmann
mats at wichmann.us
Sun Feb 19 18:10:06 EST 2023
On 2/19/23 14:06, Dieter Maurer wrote:
> Azizbek Khamdamov wrote at 2023-2-19 19:03 +0500:
>> ...
>> Example 2 (weird behaviour)
>>
>> file = open("D:\Programming\Python\working_with_files\cities.txt",
>> 'r+') ## contains list cities
>> # the following code DOES NOT add new record TO THE BEGINNING of the
>> file IF FOLLOWED BY readline() and readlines()# Expected behaviour:
>> new content should be added to the beginning of the file (as in
>> Example 1)
>> file.write("new city\n")
>>
>> file.readlines()
>> file.close()
>>
>> I could not find anything in documentation to explain this strange
>> behaviour. Why is this happening?
>
> The effect of "r+" (and friends) is specified by the C standard.
>
> The Linux doc (of `fopen`) tells us that ANSI C requires that
> a file positioning command (e.g. `seek`) must intervene
> between input and output operations. Your example above violates
> this condition. Therefore, weird behavior is to be expected.
If this isn't sufficiently described, someone should raise an issue
against the Python docs. I know that many concepts are "inherited from"
environments generally in the POSIX space and the C language, because
that's where Python was hatched (all of which makes perfect sense to me,
who's been working in those spaces for...ever), but a Python programmer
shouldn't have to read the ISO C standard (which is not free, although
you can find copies on-line), or the POSIX standard (which also is not
free, though manpages for systems like Linux cover the same material),
in order to figure out how Python is going to work.
More information about the Python-list
mailing list