Reputation: 23
I want to grab all the words from a .txt file and put them in a list with each word as an element of the list. The words are separated by line breaks in the .txt. My code so far is:
with open('words.txt', "r") as word_list:
words = list(word_list.read())
However, this piece of code just puts each letter of the .txt as its own element in my list. Any ideas?
Upvotes: 1
Views: 10565
Reputation: 13
See Here :
ashu='Hello World1'
ashu.split()
This would split the words based on the spaces between them.
And if you want to split based on any other character instead of space you could do it like
ashu.split('YOUR CHARACTER')
Upvotes: 0
Reputation: 298196
Get rid of .read()
:
words = list(word_list)
Without .read()
, you're turning the file handle into a list, which gives you a list of lines. With .read()
, you get a big list of characters.
Upvotes: 2
Reputation: 3314
with open('words.txt', "r") as word_list:
words = word_list.read().split(' ')
Upvotes: 4