Python Program to Append to a File
Appending to a file means adding new data or information to the existing contents of a file without deleting the existing content
Python Code :
The below Python program appends a string to a file:
# Define the filename and the string to append filename = "example.txt" string_to_append = "This is a new line to append." # Open the file in append mode with open(filename, "a") as file: # Use the write() method to write the string to the file file.write("\n" + string_to_append) # Print a message to confirm that the string was appended print("The string was successfully appended to the file.")
In this program, we first define the filename and the string that we want to append by assigning them to the variables filename and string_to_append, respectively.
We then open the file using the open() function with the mode parameter set to “a”, which stands for “append”. This mode opens the file for writing, but instead of overwriting the existing contents, it appends new data to the end of the file.
Inside the with block, we use the write() method of the file object to write the string to the file. We prepend the string with a newline character ("\n") to ensure that it appears on a new line.
Finally, we print a message to confirm that the string was successfully appended to the file.
You can replace the filename and string_to_append variables with any other filename and string to append. Note that if the file does not exist, it will be created when you open it in append mode.