1

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?

3 Answers 3

4
with open('words.txt', "r") as word_list:
    words = word_list.read().split(' ')
1
  • A superior solution if there are multiple words to a line.
    – holdenweb
    Jan 24, 2013 at 5:27
2

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.

2
  • D'oh I was sort of close. Thank you! One last thing, how can I get rid of the line break \n? Do I need to use regex?
    – Biiiiiird
    Jan 24, 2013 at 5:26
  • @Biiiiiird: In that case, you can just use word_list.read().split(). If you don't pass an argument to .split(), it'll split on all of the whitespace it can find (newlines, spaces and tabs).
    – Blender
    Jan 24, 2013 at 5:28
0

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')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.