Writing and appending

A file object is called f. It is neither a technique nor a unique character. You’ll see that I use f.write(), f.read(), and f.close() in the tutorials and further explanations, but you are free to substitute any character or word of your own.

“w” mode:

W stands for write in this context. Text is added to a file using the function f.write() after it has been opened or created. The text is enclosed in double quote marks and closing parenthesis. The write mode of the opening file has the restriction that it overwrites any previously stored data. It has no negative effects for freshly generated files, but it erases past data from existing files because f.write() overwrites it.

“a” mode:

Here, “a” stands for append mode. Similar to how appends in English refer to adding anything to the end of a written document, this mode serves the same purpose. When we utilize the term “a,” as opposed to the write mode, it adds new text at the end of the existing content. Text added to the file in append mode is added using the same function, f.write(). It’s important to keep in mind that append mode can be used to write into an empty file as well as create a new file if one with the identical name doesn’t already exist.

“r+” mode:

We would study both reading and creating a file at the same time, as I mentioned at the beginning of the explanation. R+ mode, however, combines reading and appending more so than reading and writing. When a file is opened in this mode, we can use the f.read() and f.write() functions to print the content that already exists and add to it.

If you are writing in append mode, begin your text with a blank space or newline character (\n), as the compiler will otherwise start the line from the last word or full stop without any blank spaces because the curser is positioned immediately after the last character in append mode. Therefore, even though some habits may not be very helpful right now, it is always recommended to embrace those that may be useful to you in the future.

f.close()

When we are through using a file, we shut it using f.close(). Closing a file after use is a good idea since, regardless of the mode you opened it for, it will be locked for that particular use and cannot be accessed from outside the program, even through the file browser.

Shubhajna Rai
Shubhajna Rai

A Civil Engineering Graduate interested to share valuable information with the aspirants.

Leave a Reply

Your email address will not be published. Required fields are marked *

Get the latest updates on your inbox

Be the first to receive the latest updates from Codesdoc by signing up to our email subscription.

    StudentProjects.in