将读取的文件放在目录中

时间:2013-11-26 15:16:56

标签: python string file-io directory

所以我正在编写一个函数来打开一个文件,读取它并将它的内容放在字典中。

基本上我正在阅读的文件如下:

Bread 10
Butter 6
Cheese 9
Candy 11
Soda 5

我想确保我的字典会有这种形式:

{ 'bread': 10, 'butter': 6, 'cheese': 9, 'candy': 11, 'soda': 5 }

那么,我怎样才能确保单词保持字符串并且我会将数字设为int

到目前为止,这是我打开文件的方法,但不知道如何继续。

def preberi_inventar(dn0501):
    f = open("dn0501.txt", "r")
    line = f.readlines()
    f.close()

2 个答案:

答案 0 :(得分:2)

d = {}
with open("dn0501.txt", "r") as f:
    for line in f:
       key, val = line.split()
       d[key] = int(val)

答案 1 :(得分:1)

我认为它可能是这样的:

def preberi_inventar(dn0501):
    with open("dn0501.txt", "r") as f:
        return dict([row.split() for row in f])