Appending a file
The standard Python implementation (CPython) has the provision for appending a file. If we open a file again in write mode and add some information, earlier information is erased, and new information is overwritten. However, MicroPython does not have this functionality. We can, however, append a file with a clever trick. We first open the file to be appended in read mode and save the contents to the variable. Then, we add another string to that variable and write the variable to the file to be appended. This will append the file. The following program demonstrates that:
with open('HenryV.txt') as file_handle: file_data = file_handle.read() file_data = file_data + '\nHenry V, William Shakespeare' with open('HenryV.txt', 'w') as file_handle: file_handle.write(file_data) with open('HenryV.txt') as file_handle: print(file_handle.read())