Layla
Layla

Reputation: 5466

reading a text with blank lines in Python

I have a text in the following format:

In the Grimms' version at least, she had the order from her mother to stay strictly on the path.
A mean wolf wants to eat the girl and the food in the basket. 

He secretly stalks her behind trees and bushes and shrubs and patches of little grass and patches of tall grass.

Then the girl arrives, she notices that her grandmother looks very strange. Little Red then says, "What a deep voice you have!" ("The better to greet you with"), "Goodness, what big eyes you have!".

I want to read it line by line and split the words to be used later, I have done the following:

def readFile():
    fileO=open("text.txt","r")
    for line in fileO:
        word=line.split()
        for w in word:
            print w

The problem is that it only prints the last line in a sort of a list, but the other lines are not printed. The output is like this:

['Then', 'the', 'girl', 'arrives,', 'she', 'notices', 'that', 'her', 'grandmother', 'looks', 'very', 'strange.', 'Little', 'Red', 'then', 'says,', '"What', 'a', 'deep', 'voice', 'you', 'have!"', '("The', 'better', 'to', 'greet', 'you', 'with"),', '"Goodness,', 'what', 'big', 'eyes', 'you', 'have!".']

Repeated like n times, I have tried to put the for w in word outside the outer loop, but the results are the same. What am I missing?

Upvotes: 1

Views: 52

Answers (1)

Padraic Cunningham
Padraic Cunningham

Reputation: 180512

If you want the lines of words split into individual lists:

with open(infile) as f:
    lines = [line.split()for line in f]
    print(lines)
[['In', 'the', "Grimms'", 'version', 'at', 'least,', 'she', 'had', 'the', 'order', 'from', 'her', 'mother', 'to', 'stay', 'strictly', 'on', 'the', 'path.'], ['A', 'mean', 'wolf', 'wants', 'to', 'eat', 'the', 'girl', 'and', 'the', 'food', 'in', 'the', 'basket.'], [], ['He', 'secretly', 'stalks', 'her', 'behind', 'trees', 'and', 'bushes', 'and', 'shrubs', 'and', 'patches', 'of', 'little', 'grass', 'and', 'patches', 'of', 'tall', 'grass.'], [], ['Then', 'the', 'girl', 'arrives,', 'she', 'notices', 'that', 'her', 'grandmother', 'looks', 'very', 'strange.', 'Little', 'Red', 'then', 'says,', '"What', 'a', 'deep', 'voice', 'you', 'have!"', '("The', 'better', 'to', 'greet', 'you', 'with"),', '"Goodness,', 'what', 'big', 'eyes', 'you', 'have!"']]

for a single list use lines = f.read().split()

Upvotes: 2

Related Questions