我的文件格式如下:Lee:18Mike:22John:31
我想读取该文件的每一行记录并将之存储为如下格式的字典:{"Lee":"18", "Mike":"22", "John":"31"}
请大神不吝赐教, 非常感谢!
欢迎选择我的课程,让我们一起见证您的进步~~
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
with open('test.txt', 'r') as f: result = dict(line.strip().split(':') for line in f if line) print(result)
Questions I answered: Python-QA
Questions I answered: Python-QA