Say I have the following in a text file:
car
apple
bike
book
How can I read it and put them into a dictionary or a list?
Reading them into a list is trivially done with readlines()
:
f = open('your-file.dat')
yourList = f.readlines()
If you need the newlines stripped out you can use ars' method, or do:
yourList = [line.rstrip('\n') for line in f]
If you want a dictionary with keys from 1 to the length of the list, the first way that comes to mind is to make the list as above and then do:
yourDict = dict(zip(xrange(1, len(yourList)+1), yourList))
words = []
for word in open('words.txt'):
words.append(word.rstrip('\n'))
The words
list will contain the words in your file. strip
removes the newline characters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With