文章详情页
Python读取文件每行记录并转存为字典格式的数据
浏览:122日期: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
相关文章:
1. node.js - Vue+Webpack在dev环境下没有问题build后出现莫名错误2. node.js - nodejs+express+vue3. javascript - vue2.0中使用vue2-dropzone的demo,vue2-dropzone的github网址是什么??百度不到。4. objective-c - ios 怎么实现微信联系列表 最好是swift5. vue计算属性怎么样与for结合使用6. PHP能实现百度网盘的自动化么?7. angular.js - vue/react 渲染内容抖动8. Python 子类能否覆盖全局函数?9. javascript - vue上传图片,并显示在页面中的插件10. kv存储 - 怎样用 Redis 缓存微博的评论列表?
排行榜
