Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from a plain text file

Tags:

python

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?

like image 686
babikar Avatar asked Dec 10 '22 14:12

babikar


2 Answers

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))
like image 151
Michael Mrozek Avatar answered Dec 27 '22 07:12

Michael Mrozek


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.

like image 42
ars Avatar answered Dec 27 '22 07:12

ars