Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

python - Reading from a plain text file

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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('
') 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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...