文章詳情頁(yè)
Python讀取文件每行記錄并轉(zhuǎn)存為字典格式的數(shù)據(jù)
瀏覽:154日期:2022-08-16 16:49:50
問(wèn)題描述
我的文件格式如下:Lee:18Mike:22John:31
我想讀取該文件的每一行記錄并將之存儲(chǔ)為如下格式的字典:{'Lee':'18', 'Mike':'22', 'John':'31'}
請(qǐng)大神不吝賜教, 非常感謝!
問(wèn)題解答
回答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)
我回答過(guò)的問(wèn)題: Python-QA
相關(guān)文章:
1. boot2docker無(wú)法啟動(dòng)2. docker-compose中volumes的問(wèn)題3. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””4. docker安裝后出現(xiàn)Cannot connect to the Docker daemon.5. java - SSH框架中寫(xiě)分頁(yè)時(shí)service層中不能注入分頁(yè)類(lèi)6. docker網(wǎng)絡(luò)端口映射,沒(méi)有方便點(diǎn)的操作方法么?7. nignx - docker內(nèi)nginx 80端口被占用8. javascript - mock.js可以存儲(chǔ)數(shù)據(jù)嗎9. node.js - antdesign怎么集合react-redux對(duì)input控件進(jìn)行初始化賦值10. java - Spring事務(wù)回滾問(wèn)題
排行榜

熱門(mén)標(biāo)簽
網(wǎng)公網(wǎng)安備