Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16506

why does Python read(3) seek to end of file

$
0
0

I am trying to understand file IO in Python, with the different modes for open, and reading and writing to the same file object (just self learning).

I was surprised by the following code (which was just me exploring):

with open('blah.txt', 'w') as f:    # create a file with 13 characters    f.write("hello, world!")with open('blah.txt', 'r+') as f:    for i in range(5):        # write one character        f.write(str(i))        # then print current position and next 3 characters        print(f"{f.tell()}: ", f"{f.read(3)}")with open('blah.txt', 'r') as f:    # look at how the file was modified    print(f.read())

Which output:

1:  ell14:  15:  16:  17:  0ello, world!1234

As I expected, the first character was overwritten by 0, then the next 3 characters read were ell, but I expected the 1 to be written over the o in hello, then the next 3 characters read to be , w.

I'm reading the docs here, but I don't see where it explains the behavior that I observed.

It appears that the first read, no matter what the size, seeks to the end of the file.

Can anyone provide a link to where it explains this in the docs?

I tried searching for a similar question on this site, but while there were many questions related to read, none that I found mentioned this behavior.

UPDATE

After more exploration, it is not the first read that seeks to the end of the file, but rather the second write that does. Again, I'm not sure why, which is why I'm hoping to find somewhere in the docs that explains this behavior.

Here's my change to the code above that shows that it's not the first read:

with open('blah.txt', 'w') as f:    # create a file with 13 characters    f.write("hello, world!")with open('blah.txt', 'r+') as f:    for i in range(3):        # write one character        f.write(str(i))        # then print current position and next 3 characters        print(f"{f.tell()}: ", f"{f.read(3)}")        print(f"{f.tell()}: ", f"{f.read(3)}")with open('blah.txt', 'r') as f:    # look at how the file was modified    print(f.read())

Which output:

1:  ell4:  o, 14:  14:  15:  15:  0ello, world!12```

Viewing all articles
Browse latest Browse all 16506

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>