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