Reading from a text file

Let's say that in a text file there is the following:

car
apple
bike
book

How can I read it and put it in a dictionary or list?

+3
source share
4 answers

Reading them into a list is trivially done with readlines():

f = open('your-file.dat')
yourList = f.readlines()

If you need a new line, you can use the ars method or do:

yourList = [line.rstrip('\n') for line in f]

If you need a dictionary with keys from 1 to the length of the list, the first way that comes to mind is to make a list as described above, and then do:

yourDict = dict(zip(xrange(1, len(yourList)+1), yourList))
+7
source
words = []
for word in open('words.txt'):
    words.append(word.rstrip('\n'))

The list wordswill contain the words in your file. stripremoves newline characters.

+1

Python.

lines = open('filename.txt', 'r').readlines()
0

You can use the file withas follows. This is called the context manager and automatically closes the file at the end of the backing block.

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

If you want to do this without a context manager, you must close the file yourself

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

Otherwise, the file remains open at least as long as it fis still in the area

0
source

Source: https://habr.com/ru/post/1755445/


All Articles