Python Program - Append to a File
https://www.theitroad.com
Here's a Python program to append data to an existing file:
# open the file in append mode with open("filename.txt", "a") as file: # get input from the user data = input("Enter data to append: ") # write the data to the file file.write(data + "\n") # print a message to confirm that data has been appended print("Data has been appended to the file.")
In this program, we use the with
statement to open the file in append mode. This ensures that the file is automatically closed after we have finished working with it.
We prompt the user to enter the data that they want to append to the file using the input()
function. We then write this data to the file using the write()
method. We add a newline character (\n
) to the end of the data so that each new entry is written on a new line in the file.
Finally, we print a message to confirm that the data has been appended to the file.