Why does read() not work with 'w+' or 'r+' mode in open() function python
Solution 1:
with open(file_name, 'r') as o:
print(o.read())
outputs hello, as you say.
with open(file_name, 'r+') as o:
print(o.read())
outputs hello as well. I don't know why you say that it outputs nothing.
with open(file_name, 'w+') as o:
o.write('hello')
print(o.read())
outputs nothing because 'w+' tosses out the current contents of the file, and then after you write hello to the file, the file pointer is at the end of the file, and the read attempts to read from that point. To read what you've written, you need to seek back to the start of the file first:
with open(file_name, 'w+') as o:
o.write('hello')
o.seek(0)
print(o.read())
prints:
hello
See https://docs.python.org/3/library/functions.html#open for more details.
Solution 2:
with open(file_name, 'r') as o:
print(o.read())
Outputs hello
because the file is opened for reading
with open(file_name, 'r+') as o:
print(o.read())
Also outputs hello
because the file is still opened for reading
with open(file_name, 'w+') as o:
print(o.read())
Outputs nothing becuase the file is truncated.
See https://docs.python.org/3/library/functions.html#open for more details.