Reading from a plain text file

后端 未结 4 883
天涯浪人
天涯浪人 2020-12-11 08:24

Say I have the following in a text file:

car
apple
bike
book

How can I read it and put them into a dictionary

4条回答
  •  天涯浪人
    2020-12-11 08:42

    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

提交回复
热议问题