0

So I've been messing around with write.

In my folder, I have a text file called test.txt which contains abcdefg.

If I run the following script:

with open('test.txt', mode='r+') as f:
    f.write('test')

the test.txt file now contains testefg

And for some reason, if I instead run the following script: (starting back with abcdefg in test.txt)

with open('test.txt', mode='r+') as f:
    f.read()
    f.write('test')

Now the test.txt file contains abcdefgtest

Also, I don't really understand what mode='r+' does because I can't find it in any documentation. Some sources on the internet said that it was for both reading and writing in the file. I suspect it behaves the same as '+'

Mateo Vial
  • 658
  • 4
  • 13
  • 2
    Does this answer your question? [Difference between modes a, a+, w, w+, and r+ in built-in open function?](https://stackoverflow.com/questions/1466000/difference-between-modes-a-a-w-w-and-r-in-built-in-open-function) – Wouter May 31 '22 at 14:00
  • 7
    A file has an *internal file pointer*, and depending on where it is, that's where you write. `read` moves the file pointer to the end… – deceze May 31 '22 at 14:01
  • Alright, that's clear. – Mateo Vial May 31 '22 at 14:05
  • 1
    @Wouter my question was more precisely about why adding `f.read()` in a line makes a difference, and not entirely about what the modes did, but thank you for the link that was useful – Mateo Vial May 31 '22 at 14:06

0 Answers0