Reputation: 25
When ever I use the open with the 'r+' or the 'w+' parameters, It doesn't want to read the text file.
Inside Text Document:
hello
Python Code Examples:
code:
with open(file_name, 'r') as o:
print(o.read())
output:
hello
code:
with open(file_name, 'r+') as o:
print(o.read())
output:
code:
with open(file_name, 'w+') as o:
o.write('hello')
print(o.read())
output:
I also tried setting o.read()
as a variable and then printing it, but there still was no output. If someone could please tell me why this happens, that would be great.
Upvotes: 2
Views: 2040
Reputation: 23089
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.
Upvotes: 1
Reputation: 51
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.
Upvotes: 1