文章詳情頁
Python讀取文件每行記錄并轉(zhuǎn)存為字典格式的數(shù)據(jù)
瀏覽:100日期: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
相關(guān)文章:
1. python 利用subprocess庫調(diào)用mplayer時發(fā)生錯誤2. python文檔怎么查看?3. python - Pycharm的Debug用不了4. javascript - 關(guān)于apply()與call()的問題5. datetime - Python如何獲取當(dāng)前時間6. javascript - nginx反向代理靜態(tài)資源403錯誤?7. html - eclipse 標(biāo)簽錯誤8. 請問PHPstudy中的數(shù)據(jù)庫如何創(chuàng)建索引9. 安全性測試 - nodejs中如何防m(xù)ySQL注入10. python - pycharm 自動刪除行尾空格
排行榜

熱門標(biāo)簽