1. 程式人生 > >python 將txt文件轉換成字典

python 將txt文件轉換成字典

odin 嵌套 isp 實現 spa clas sha utf cbe

txt 文件內容如下

liu 123
shao 456
hui 789

將上述txt文件轉換成字典格式
實現思路:
定義一個空列表,按行讀取txt文件,然後轉換成嵌套列表,進而通過dict方法將嵌套列表轉換成字典(左邊為key,右邊為value)
技術分享圖片
1 with open(user_list,r,encoding=utf-8) as f:
2         dic=[]
3         for line in f.readlines():
4               line=line.strip(\n) #去掉換行符\n
5                b=line.split(
) #將每一行以空格為分隔符轉換成列表 6 dic.append(b) 7 dic=dict(dic) 8 print(dic)
View Code





python 將txt文件轉換成字典