Reputation: 457
I want to make a simple function that writes two words to a file each on a new line. But if I run this code it only writes "tist - tost" to the file.
Code:
def write_words(word1, word2):
w = open("output.txt", "w")
w.write(word1 + " - " + word2 + '\n')
w.close()
write_words("test", "tast")
write_words("tist", "tost")
Output:
tist - tost
How can I write the two phrases to the file?
Upvotes: 3
Views: 76
Reputation: 107287
You need to open your file in append mode, also as a more pythonic way for opening a file you can use with
statement which close the file at the end of block :
def write_words(word1, word2):
with open("output.txt", "a") as f :
f.write(word1 + " - " + word2 + '\n')
Upvotes: 9