文章详情页
Python读取文件每行记录并转存为字典格式的数据
浏览:36日期:2022-08-16 16:49:50
问题描述
我的文件格式如下:Lee:18Mike:22John:31
我想读取该文件的每一行记录并将之存储为如下格式的字典:{'Lee':'18', 'Mike':'22', 'John':'31'}
请大神不吝赐教, 非常感谢!
问题解答
回答1: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回答2:
with open(’test.txt’, ’r’) as f: result = dict(line.strip().split(’:’) for line in f if line)print(result)
我回答過的問題: Python-QA
相关文章:
排行榜
