tags:

views:

84

answers:

4

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?

+3  A: 

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))
Michael Mrozek
the keys can be like 1 2 3 4
babikar
It's a good habit to use `with open('your-file.dat') as f:` so that the file handle is closed properly.
blokeley
@blokeley It is, but depending on version that can involve importing from `__future__`, and I'm not going to bother explaining all that for a two-line code snippet
Michael Mrozek
A: 

This is covered pretty thoroughly in the Python tutorial.

lines = open('filename.txt', 'r').readlines()
Chris B.
A: 
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.

ars
A: 

You can use the file with with like this. This is called a context manager and automatically closes the file at the end of the indented block

with open('data.txt') as f:
    words = f.readlines()

If you want to do it without a context manager, you should close the file yourself

f = open('data.txt')
words = f.readlines()
f.close()

Otherwise the file remains open at least as long as f is still in scope

gnibbler