Skip to content

Document Operation in Python (Write)


Properties of write operation (w):

  • If the file is not exist it will create a new file.
  • If the file is existed, the old / original data inside will be replaced by the new data, if "w" mode is used.

Flow of writing data on a document:

1. Open
2. Write
3. Save
4. Close

Usage

file-operation-write.py

Example without using flush()

py
import time

file = open("./write-test.txt", mode="w")
file.write("Hello, World") # Write at the ram

time.sleep(10) # Blocking
# It will write on file/disk when end of the programme
file.close()

Info

  • When calling write() function, the data actually not really write on the file yet. It's write at the ram.
  • Only flush() method is called, then buffered data will be flushed. With this function the will make the data eventually write / flushed on to the disk / file.
  • Even without flush() function is being used, it will flushing the buffered data to the file when the programme is end.
  • Since the time.sleep(10) (blocking code) is used, forcing the code stop (CTRL + c) will also flush the buffered data into a file.

Example with flush()

py
import time

file = open("./write-test.txt", mode="w")
file.write("Hello, World") # Write at the ram
file.flush() # The data write on disk immediately
time.sleep(10) # Blocking
file.close()

The file output:

write-test.txt

text
Hello, World

Info

When the file.flush() is being use, the data write on disk immediately, even the program is blocking.

Conclusion

NoFlowCode
1Openf = open("file_path", mode="w")
2Writef.write("Hello, World")
3Savef.flush()
4Closef.close()

Special Info

f.close() actually has built in flush() function. That will automatically flush buffered data before closing the file. So. with the code of f.close() the flush() function will work even its not call.