Search code examples
pythonfilefile-descriptor

Python write and read is not working with same file Descriptor


I'm using the below code to write to file and read the content which i have write. However, it is giving me empty content when i read it.

text = 'Blah1'

with open('my_file.txt', 'r+') as file:
    file.write(text)
    print 'Content created.\n'
    print 'Now reading from file.\n'
    Content = file.read()
    print 'Content is : ' + Content

I think i'm missing something or misunderstood something. Any explain on this why this wont work would be appreciate.

PS: It work if i use different file descriptors.


Solution

  • You have to reposition the current read/write position with seek as described here Confused by python file mode "w+"