0

the output:

Before flush():
 He

After flush():
 llo World !

why the fileobject not clearing the whole gfg.txt while I am making it read only two char on the txt file why does that have an impact on not cleaning the whole file?

# program to demonstrate the use of flush()
 
# creating a file
fileObject = open("gfg.txt", "w+")
 
# writing into the file
fileObject.write("Hello World !")
 
# closing the file
fileObject.close()
 
 
# opening the file to read its content
fileObject = open("gfg.txt", "r")
 
# reading the contents before flush()
fileContent = fileObject.read(2)
 
# displaying the contents
print("\nBefore flush():\n", fileContent)
 
 
# clearing the input buffer
fileObject.flush()
 
# reading the contents after flush()
# reads nothing as the internal buffer is cleared
fileContent = fileObject.read()
 
# displaying the contents
print("\nAfter flush():\n", fileContent)
 
# closing the file
fileObject.close()
  • 5
    Could you clarify what you think calling `flush` on a read only stream does? – Brian61354270 Aug 19 '23 at 20:01
  • 3
    Because the purpose of `flush` is not anything at all related to what you seem to expect. I can't tell you why you don't get the result you expect, because I can't understand why you expect it. – Karl Knechtel Aug 19 '23 at 20:02
  • 3
    The purpose of flush is for OUTGOING data (i.e. a file opened in write mode), not INCOMING data (a file opened in read mode). – John Gordon Aug 19 '23 at 20:05

1 Answers1

4

Calling flush on a read only stream does nothing.

Quoting the documentation for io.IOBase.flush():

Flush the write buffers of the stream if applicable. This does nothing for read-only and non-blocking streams.

The point of flush is to flush an output buffer, where writes are queued up in memory before actual file I/O is performed. It doesn't have any use for input streams.

It also doesn't change the position of the stream, to the end or otherwise. If you want to move the stream position, use seek.

See also What is the use of buffering in python's built-in open() function?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43