【问题标题】:Put the read file in directory将读取的文件放入目录
【发布时间】:2013-12-11 19:49:25
【问题描述】:

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

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

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

【问题讨论】:

  • 第一步是开始使用line...也许你可以split 它?
  • 我已经得到答案了,还是谢谢你:)
  • ups,没看到 :)

标签: python string file-io directory


【解决方案1】:
d = {}
with open("dn0501.txt", "r") as f:
    for line in f:
       key, val = line.split()
       d[key] = int(val)

【讨论】:

  • 要按要求获取号码,您应该使用d[key] = int(val)
  • @Matthias 我的错。谢谢。更正了帖子。
【解决方案2】:

我觉得可以是这样的:

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

【讨论】:

    猜你喜欢
    • 2019-11-24
    • 2012-06-25
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多