Document Operation in Python (Write)
Properties of write operation (w):
- If the file is
not existit willcreate a new file. - If the file is
existed, theold / 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, thenbuffered 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 alsoflush 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, WorldInfo
When the file.flush() is being use, the data write on disk immediately, even the program is blocking.
Conclusion
| No | Flow | Code |
|---|---|---|
| 1 | Open | f = open("file_path", mode="w") |
| 2 | Write | f.write("Hello, World") |
| 3 | Save | f.flush() |
| 4 | Close | f.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.