"w" vs "r+"

my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "w")

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


why does this code work, but when "w" is replaced with "r+", does not?


w = write, all it is doing is writing the file. There is no read.

w+ is both write and read in one. (writes the file too if it does not exist.)

r = read only

r+ is read and write (will write to file but not create)

Also do this instead of what you have

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

with open("output.txt", "w+") as file:
    for x in my_list:
        my_file.write(str() + "\n")

This will close the file automagically after it completes the code.