python将txt文件读取为字典的示例
作者:weixin_39012047 时间:2023-02-25 15:57:16
如下所示:
# -*- 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')
来源:https://blog.csdn.net/weixin_39012047/article/details/81538497
标签:python,txt,字典
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3+PyQt5实现自定义窗口部件Counters
2021-05-21 10:47:47
![](https://img.aspxhome.com/file/2023/7/69487_0s.png)
php快递单号查询接口使用示例
2023-10-25 07:39:55
Python面向对象程序设计之继承、多态原理与用法详解
2023-07-08 18:17:52
![](https://img.aspxhome.com/file/2023/6/82716_0s.png)
ASP如何使用CDONTS来发送电子邮件?
2010-06-05 12:35:00
设计和布局之间的思考
2008-10-09 13:06:00
通过gradio和摄像头获取照片和视频实现过程
2023-07-08 18:02:30
![](https://img.aspxhome.com/file/2023/8/62848_0s.png)
Python数学建模库StatsModels统计回归简介初识
2021-05-05 04:57:02
Python摸鱼神器之利用树莓派opencv人脸识别自动控制电脑显示桌面
2021-01-12 07:31:45
![](https://img.aspxhome.com/file/2023/1/97531_0s.jpg)
python实现自动更换ip的方法
2023-06-16 21:43:06
SQLServer 连接 EXCEL
2009-07-09 19:00:00
Python编程mac下使用pycharm小技巧
2022-10-21 19:23:52
![](https://img.aspxhome.com/file/2023/9/75119_0s.jpg)
Python 通过调用接口获取公交信息的实例
2023-06-17 21:16:46
Python实现简单过滤文本段的方法
2023-11-24 16:19:22
python递归&迭代方法实现链表反转
2021-05-04 20:42:04
![](https://img.aspxhome.com/file/2023/7/102327_0s.png)
浅谈Python中列表生成式和生成器的区别
2023-03-21 11:50:39
基于php权限分配的实现代码
2023-11-14 11:10:49
![](https://img.aspxhome.com/file/2023/3/94503_0s.png)
利用python清除移动硬盘中的临时文件
2022-12-07 21:43:11
![](https://img.aspxhome.com/file/2023/7/67797_0s.jpg)
Firefox 3.6新功能预览
2009-12-01 14:23:00
python实现获取Ip归属地等信息
2022-10-24 00:13:31
安装pytorch时报sslerror错误的解决方案
2022-01-01 05:20:53
![](https://img.aspxhome.com/file/2023/7/95387_0s.jpg)