Code giving error

with open(“sid.txt”,“w+”) as f:
f.write(“ajay siddartha”)
print(f.read())

this is not runnung

hey @ajaysiddartha ,
is it giving any error ? or just not printing anything ?

not printing anything

you can’t do this like this , when you are using w+ as the operation to open file, you can write in it. You can’t read it then.

But if you change this operation to r then you will get the correct output.

but w+ should do both the things no

Yea you are right.
if you still to work with the same code , then you need to add a line f.seek(0) , it means while you have written to the file , then you are currently at the end of file , means if we read now we won’t get anything.
So for that we need to get at the first position, so we do so , and hence now we can read easily.

with open(“sid.txt”,“w+”) as f:
f.seek(0)
f.write(“ajay siddartha”)
print(f.read())

even not primting

no do it like.

with open(“sid.txt”,“w+”) as f:
>>> f.write(“ajay siddartha”)
>>> f.seek(0)
>>> print(f.read())

it will work.

yes now working …but why it was not working in the below way

with open(“sid.txt”,“w+”) as f:
f.seek(0)
f.write(“ajay siddartha”)
print(f.read())

because in this still we are end of the file before reading.
you need to place the seek call correctly

but seek is coming before read function no…before reading it should move the cursor to start point

after write function and before read

ya thats ok but why not in that way…before reading ,everytime it will move the cursor to the starting point

see , first you write “hello” , then your cursor will be at 5 position.
okay , so if you read then you won’t get anything.
but now, if we do f.seek(0) , then this will move the cursor to starting.
so now if you will read , then you can read directly as f.read() and it works.

ok understood…and one more thing will the data inside file will be saved when the file is closed

yes , it will be saved.

so everytime this is ran ,the write function will run …
so will not the text append again and again?
if not then why?

there are multiple methods to perform while opening a file.
So, when we use w or w+, then it will first empty the file and then will again write the text you do using write.

for appending you can use , a

with open(“sid.txt”,“w+”) as f:

f.write("ajay siddartha")
f.seek(0)

print(f.read())

with open(“sid.text”,“a”) as f:
f.write(“siddartha ajay”)

with open(“sid.text”,“r”) as f:
print(f.read())

so we have to do this for appending and reading it

Yeah its correct but after the above code, your cursor will be at beginning , so your second call will overwrite the first one.