[Tutor] Semantic Error: Trying to access elements of list and append to empty list with for loop

Olaoluwa Thomas thomasolaoluwa at gmail.com
Thu Jun 2 13:05:43 EDT 2016


Hi Tutor,

I'm trying to parse words in a file line by line and place all words into
another list but I keep getting a list with nested lists.
I would normally pore over it and go to google and fix my problems but this
one escapes me and frankly, I'm tired of being stuck in the same place for
almost a week.

Here's the code:
fname = raw_input('Enter file name:\n')
try:
    fhand = open(fname)
except:
    print 'File cannot be found or opened:', fname
    exit()
lst = list()
for line in fhand:
    words = line.split()
    #print words (this was a test that a portion of my code was working)
    lst.append(words)
print lst

A text file with the following contents
"But soft
what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief"

would give me the output in the attached screenshot
[image: Inline image 2]

whereas I want only one list containing strings not nested lists.

Any help would be appreciated.

*Warm regards,*

*Olaoluwa O. Thomas,*
*+2347068392705*


More information about the Tutor mailing list