![]() |
VOOZH | about |
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows:
These modes are ideal when you want to preserve existing content while adding more. Let's look at some examples:
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is LondonToday
Output of Readlines after writing
Tomorrow
Explanation:
In the above example of file handling, it can be seen that the data is not appended from the new line. This can be done by writing the newline '\n' character to the file.
Output:
Output of Readlines after appending
This is Delhi
This is Paris
This is London
TodayTomorrow
Explanation:
Note:β\nβ is treated as a special character of two bytes.
with statement is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Unlike the above implementations, there is no need to call file.close() when using with statement.
Output:
Hello
This is Delhi
This is Paris
This is London
Today
Explanation:
Note: To know more about with statement click here.
This approach uses the shutil.copyfileobj() method to append the contents of another file (source_file) to 'file.txt'. This can be useful if you want to append the contents of one file to another without having to read the contents into memory first.
Explanation:
Related article: File Handling in Python