Biiiiiird
Biiiiiird

Reputation: 23

How can I add each word in a .txt file to a list in Python?

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

Answers (3)

Ashutosh Tiwari
Ashutosh Tiwari

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

Blender
Blender

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

Jun HU
Jun HU

Reputation: 3314

with open('words.txt', "r") as word_list:
    words = word_list.read().split(' ')

Upvotes: 4

Related Questions