Search code examples
pythonrownewline

How Can I Remove Newline and Add All Words To a List


I have a txt file it contains 4 lines. (like a poem) The thing that I want is to add all words to one list. For example the poem like this :

I am done with you,

Don't love me anymore

I want it like this : ['I', 'am', 'done', 'with', 'you', 'dont', 'love', 'me', 'anymore']

But I can not remove the row end of the first sentence it gives me 2 separated list.

romeo = open(r'd:\romeo.txt')
list = []

for line in romeo:
    line = line.rstrip()
    line = line.split()
    list = list + [line]
print(list)

Solution

  • with open(r'd:\romeo.txt', 'r') as msg:
        data = msg.read().replace("\n"," ")
    
    data = [x for x in data.split() if x.strip()]