Appending to a file

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")
Report a Glow concern
Cookie policy  Privacy policy

Glow Blogs uses cookies to enhance your experience on our service. By using this service or closing this message you consent to our use of those cookies. Please read our Cookie Policy.