如下所示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
# -*- coding: utf-8 -*-
# @Time :18-8-2 下午3:23
import sys
reload (sys)
sys.setdefaultencoding( 'utf8' )
fp = open ( "file" , "r" )
sample = fp.readlines()
result_list = [] # 创建一个空列表
with open ( 'file' , 'w' ) as f:
for line in sample:
result_dict = {}
try :
sample_ = line.split( ' ' ) #按照空格进行文件中每一行的切割
result_dict[sample_[ 0 ].split( ':' , 1 )[ 0 ]] = sample_[ 0 ].split( ':' , 1 )[ 1 ] #分别取:前后的数据为key和value
result_dict[sample_[ 2 ].split( ':' , 1 )[ 0 ]] = sample_[ 2 ].split( ':' , 1 )[ 1 ]
result_dict[sample_[ 4 ].split( ':' , 1 )[ 0 ]] = sample_[ 4 ].split( ':' , 1 )[ 1 ]
except IndexError as s:
pass
result_list.append(result_dict)
for i in result_list:
data_value = str (i).decode( 'string_escape' ) #数据中存在中文字符,必须进行编码
f.write(data_value)
f.write( '\n' )
|
以上这篇python将txt文件读取为字典的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_39012047/article/details/81538497