Wednesday, 4 April 2018

Python: put each line of words in a list





problem:



I am trying to append words in the animals.txt into myList. The animals.txt file looks like something below.



code tried:




opena = open('animals.txt')
aread = opena.read()
myList = []
for line in aread:
myList.append(line.split("\n"))

print(myList)


animals.txt




COW
CHICKEN
DOG
RAT
MOUSE


expected output for myList:




myList = ['COW', 'CHICKEN', 'DOG', 'RAT', 'MOUSE']

Answer



Im not sure why you used the split function. Instead i think the following list comprehension will help you.



f = open('animal.txt','r')
myList = [line.strip() for line in f]
f.close()



Hope it helps.


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...