Rumah > Soal Jawab > teks badan
我的文件格式如下:
Lee:18
Mike:22
John:31
我想读取该文件的每一行记录并将之存储为如下格式的字典:
{"Lee":"18", "Mike":"22", "John":"31"}
请大神不吝赐教, 非常感谢!
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
怪我咯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)
Soalan yang saya jawab: Python-QA