Maison  >  Questions et réponses  >  le corps du texte

Python读取文件每行记录并转存为字典格式的数据

我的文件格式如下:
Lee:18
Mike:22
John:31

我想读取该文件的每一行记录并将之存储为如下格式的字典:
{"Lee":"18", "Mike":"22", "John":"31"}

请大神不吝赐教, 非常感谢!

天蓬老师天蓬老师2741 Il y a quelques jours880

répondre à tous(2)je répondrai

  • PHP中文网

    PHP中文网2017-04-18 10:31:17

    f = open('1', 'r')                  
    result = {}
    for line in f.readlines():
        line = line.strip()
        if not len(line):
            continue
        result[line.split(':')[0]] = line.split(':')[1]
    f.close()
    print result

    répondre
    0
  • 怪我咯

    怪我咯2017-04-18 10:31:17

    with open('test.txt', 'r') as f:
        result = dict(line.strip().split(':') for line in f if line)
    print(result)

    Questions auxquelles j'ai répondu : Python-QA

    répondre
    0
  • Annulerrépondre