0

I'm just beginning to learn Python 3 and am having trouble creating a list of strings from a file. Instead, it appears to be making a list of list. Each line of the text file is an element is the list. Each word is an element of a list within the first list.

I've tried google searches for creating lists from files and have read a couple of books on Python. I've also watched Udemy videos.

fname = input('Enter file name: ')
try:
   fh = open(fname)
except:
    print('File not found')
    quit()

list1 = list()
for item in fh:
    list1.append(item.rstrip().split())

print(list1)

Actual Result:

[["I'm", 'using', 'this', 'file', 'as', 'an', 'example'], ['of', 'pulling', 
  'a', 'list', 'of', 'strings', 'from', 'a', 'file'], ['Rather', 'than', 'making', 
  'each', 'word', 'an', 'element'], ["it's", 'making', 'each', 'line', 'an', 'element']]

Expected Result:

["I'm", 'using', 'this', 'file', 'as', 'an', 'example','of', 'pulling', 'a', 
 'list', 'of', 'strings', 'from', 'a', 'file', 'Rather', 'than', 'making', 'each',
 'word', 'an', 'element', "it's", 'making', 'each', 'line', 'an', 'element']
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Phillip D
  • 1
  • 2

1 Answers1

0

Use this instead:

list1.append(' '.join(item.rstrip().split()))

When you use split() method on a string, it will result in a list, so that's where you went off track, you made a list and then appended it in another list, that's why you got lists inside of list.

str.join() method will join elements of lists using the str you provide

Naman Chikara
  • 164
  • 14