python将txt文件读取为字典的示例

yipeiwu_com5年前Python基础

如下所示:

# -*- 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文件读取为字典的示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

TensorFlow深度学习之卷积神经网络CNN

TensorFlow深度学习之卷积神经网络CNN

一、卷积神经网络的概述 卷积神经网络(ConvolutionalNeural Network,CNN)最初是为解决图像识别等问题设计的,CNN现在的应用已经不限于图像和视频,也可用于时间...

Python安装Imaging报错:The _imaging C module is not installed问题解决方法

今天写Python程序上传图片需要用到PIL库,于是到http://www.pythonware.com/products/pil/#pil117下载了一个1.1.7版本的,我用的是Ce...

Python hashlib常见摘要算法详解

这篇文章主要介绍了Python hashlib常见摘要算法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Python的hashl...

详解python开发环境搭建

详解python开发环境搭建

虽然网上有很多python开发环境搭建的文章,不过重复造轮子还是要的,记录一下过程,方便自己以后配置,也方便正在学习中的同事配置他们的环境。 1.准备好安装包 1)上python官网下载...

python aiohttp的使用详解

python aiohttp的使用详解

1.aiohttp的简单使用(配合asyncio模块) import asyncio,aiohttp async def fetch_async(url): print(url)...