Create a function called write_to_file(filename, text)
that opens a file whose filename
was passed as an argument and saves the separate words from the text
argument, one word per line.
The usage of the write_to_file(filename, text)
function should be as follows:
- We provide the name of the file that will be created, e.g.,
my_filename.txt
.
- We provide the string of words as a second argument, e.g.,
"I like cats"
.
- The function creates a filename called
my_filename.txt
. The contents of the file would be:
I
like
cats
Remember that normal iterations on strings iterate over characters, not words.
The .split()
function can be used to split text into words. By default, it splits on every whitespace character:
sentence = "I learn something new everyday"
word_list = sentence.split()
>> ['I', 'learn', 'something', 'new', 'everyday']
To write to a file you need to open the file in the write ('w'
) mode and use the write()
function:
with open(filename, 'w') as f:
f.write("Hello world")
Remember to add '\n'
to every word when saving a word to the file.
Make sure you don't remove the last line in the Code Editor:
write_to_file('new_file.txt', 'I love Python')
Don't write anything else to the file. Remember – you can always check what you've written to the file. At the end of the whole code you can type:
with open('new_file.txt', 'r') as f:
print(f.read())
The result should be:
I
love
Python