Does "r+" actually do anything?


#1

In this exercise ( https://www.codecademy.com/en/courses/learn-python/lessons/file-inputoutput/exercises/the-open-function ) they say that r+ allows you to read as well as write it. I tried substituting w and r+ and I didn’t notice any differences. I didn’t have any problems with the exercise I just want to know why.



my_list = [i ** 2 for i in range(1, 11)]

my_file = open("output.txt", "r+")

for i in my_list:
  my_file.write(str(i) + "\n")
my_file.close()


and

my_list = [i ** 2 for i in range(1, 11)]

my_file = open("output.txt", "w")

for i in my_list:
  my_file.write(str(i) + "\n")
my_file.close()

do exactly the same things…at least as far as I can see. Can someone explain why to me? I’m just really curious.


#2

What it doesn’t do is truncate to zero length as w does. Open a file with w and write to it… You just replaced it.

r+ does not truncate but positions the pointer at the start of the file for reading. If you write to the file, it will be wherever the pointer is. There is actually a lot of difference between r+ and w when we think about it.


#3

Oh, cool! That would be why I didn’t notice any difference as well. Thanks! :smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.