When you append data to a file it is added after any existing file content.
After the last example the output file that the program created would contain:
This is the first line.
The second line
And the third line
Using the following code, you could append further lines onto the output file.
lines_to_write = ["This is the forth line.",
"The fifth line",
"And the sixth line"]
with open("data2.txt", "a") as input_file:
for line in lines_to_write:
input_file.write(str(line) + "\n")
The contents of data2.txt would now be:
This is the first line.
The second line
And the third line
This is the forth line.
The fifth line
And the sixth line
By appending you don’t overwrite the existing content.
Open up write.py and change it to read:
string_to_write = "How are you doing?"
with open("HelloWorld.txt", "at") as file_handler:
file_handler.write(string_to_write + "\n")
print("File appended")