The file is inside a buffer and pushes over the actual file on the storage device in future time.
However, we want to force Python to write the contents of the buffer over storage, we can use the flush() function.
Python automatically flushes the file buffers when closing them like, this function is completely called by the close() function.
But we may want to flush the data before closing any file.
f = open('out.log', 'w+') pending in output buffer. f.write('The output is \n') f.write( "My" + "work-status "+"is") f.flush() $ = 'OK. f.write(s) f.write('\n') f.write('Finally over\n') f. flush() f.close()
The flush() function forces the writing of data on disc still Pending in output buffer.
Removing Whitespaces ofter Reading from File
The read() and readline() functions explained above, read data from the file and return it in string form, and the readlines() function returns the entire file content in a list where a particular line is one item of the list.
All these read functions also read the leading and tracking whitespaces like spaces or tabs or newline characters.
If you want to remove any of these trailing and leading whitespaces, you can use strip functions (strip, I strip)
the strip() removes the given character from both ends.
the rstrip() removes the given character from the trailing end i.e., the right end.
the Istrip() removes the given character from the leading end i.e., left end.
Steps to process a file in python
The following lines list the steps that need to be followed in the order as mentioned below. The five steps to use files in your Python program are as follows
Step 1.Determine the type of file usage
Under this step, we need to decide whether we need to open the file for reading purposes that input type of usage or writing purposes like output type of usage.
If the data remains to brought in from a file to memory, then the file must remain open in a mode that supports reading such as “V” or “r+” etc.
Similarly, if the data after some processing to sent from memory to file, the file must opened in a
the mode that supports writing such as “w” or “w+” or “a” etc.
Step 2. Open the file and assign its reference to a file object or file-handle
Next, you need to open the file using open() and assign it to a filehandle on which all the file operations will perform. Just remember to open the file in the file mode that you decided on in step 1.
Step 3. Now process as required
As per the situation, you need to write instructions to process the file as desired. For example, you might need to open the file and then read it one line at a time while making some computation, and so on.
Step 4. Close the file
This is a very important step especially if you have opened the file in write mode. This is because sometimes
the last lap of data remains in buffer and not pushed on to disk until a close() operation is performed.