# open/create a file for writing example 1
file = open('sample_text.txt', 'w')
file.write("Hello,\n")
file.write("world!")
file.close()
# open/create a file for writing example 2 (using with statement)
with open('sample_text.txt', 'w') as file:
file.write("Hello,\n")
file.write("world!")
Each task below is interactive. Edit the code in the editor and click Run.
Write a Python program that does the following (remember to use \n to create new lines):
output.txt in write mode ('w')."Hulk Hogan" to the file."Ultimate Warrior" to the file."Ted Dibiase" to the file."Randy Savage" to the 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()