Writing to Files in Python 2



Interactive tasks (trinket.io)

Each task below is interactive. Edit the code in the editor and click Run.

Task 1 — Write a program that writes several lines of text to a file

Write a Python program that does the following (remember to use \n to create new lines):

Task 2 — Write a program that writes several lines of text to a file

You may have noticed that every time you write to the file, the file is overwritten completely. Modify your program so that it appends the lines to the end of the file instead of overwriting it. Remember to open the file in append mode ('a').

# open/create a file for appending 
file = open('sample_text.txt', 'a')
file.write("Hello")
file.close()