Python append to a file
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:
- Append Only (‘a’): Open the file for writing.
- Append and Read (‘a+’): Open the file for reading and writing.
When the file is opened in append mode in Python, the handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Example 1: Python program to illustrate Append vs write mode.
Output of Readlines after appending This is Delhi This is Paris This is LondonToday Output of Readlines after writing Tomorrow
Example 2: Append data from a new line
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 of Readlines after appending This is Delhi This is Paris This is London TodayTomorrow
Note: ‘\n’ is treated as a special character of two bytes.
Example 3: Using With statement in Python
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. The with statement itself ensures proper acquisition and release of resources.
Hello This is Delhi This is Paris This is London Today
Note: To know more about with statement click here.
Using the shutil module:
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.
The code uses the shutil.copyfileobj() function to copy the contents of the source_file object to a new file called file.txt. The with statement is used to open and automatically close the file, using the file object f.
The time complexity of shutil.copyfileobj() function is proportional to the size of the file being copied, as it needs to read and write every byte of the file. Therefore, the time complexity of the code is O(n), where n is the size of the source_file.
The space complexity of the code is O(1), as it does not allocate any additional memory beyond what is required for the file objects source_file and f. The shutil.copyfileobj() function copies the file contents in chunks, so it does not need to load the entire file into memory at once.
Overall, the code has a linear time complexity and constant space complexity, where the time complexity is proportional to the size of the file being copied.
Please Login to comment...