Python实现按特定格式对文件进行读写的方法示例


Posted in Python onNovember 30, 2017

本文实例讲述了Python实现按特定格式对文件进行读写的方法。分享给大家供大家参考,具体如下:

#! /usr/bin/env python
#coding=utf-8
class ResultFile(object):
  def __init__(self, res):
    self.res = res
  def WriteFile(self):
    fp = open('pre_result.txt', 'w')
    print 'write start!'
    try:
      for item in self.res:
        fp.write(item['host'])
        fp.write('\r')
        fp.write(str(item['cpu']))#write方法的实参需要为string类型
        fp.write('\r')
        fp.write(str(item['mem']))
        fp.write('\n')
    finally:
      fp.close()
      print 'write finish!'
  def ReadFile(self):
    res = []
    fp = open('pre_result.txt', 'r')
    try:
      lines = fp.readlines()#读取出全部数据,按行存储
    finally:
      fp.close()
    for line in lines:
      dict = {}
      #print line.split() #like['compute21', '2', '4']
      line_list = line.split() #默认以空格为分隔符对字符串进行切片
      dict['host'] = line_list[0]
      dict['cpu'] = int(line_list[1])#读取出来的是字符
      dict['mem'] = int(line_list[2])
      res.append(dict)
    return res
if __name__ == '__main__':
  result_list=[{'host':'compute21', 'cpu':2, 'mem':4},{'host':'compute21', 'cpu':2, 'mem':4},
         {'host':'compute22', 'cpu':2, 'mem':4},{'host':'compute23', 'cpu':2, 'mem':4},
         {'host':'compute22', 'cpu':2, 'mem':4},{'host':'compute23', 'cpu':2, 'mem':4},
         {'host':'compute24', 'cpu':2, 'mem':4}]
  file_handle = ResultFile(result_list)
  #1、写入数据
  #print 'write start!'
  file_handle.WriteFile()
  #print 'write finish!'
  #2、读取数据
  res = file_handle.ReadFile()
  print res

写入的文件:

Python实现按特定格式对文件进行读写的方法示例

每一行的数据之间其实已经加入空格。

运行结果:

write start!
write finish!
[{'mem': 4, 'host': 'compute21', 'cpu': 2}, {'mem': 4, 'host':
'compute21', 'cpu': 2}, {'mem': 4, 'host': 'compute22', 'cpu': 2},
{'mem': 4, 'host': 'compute23', 'cpu': 2}, {'mem': 4, 'host':
'compute22', 'cpu': 2}, {'mem': 4, 'host': 'compute23', 'cpu': 2},
{'mem': 4, 'host': 'compute24', 'cpu': 2}]

实现了按原有格式写入和读取。

希望本文所述对大家Python程序设计有所帮助。

Python 相关文章推荐
浅谈python 线程池threadpool之实现
Nov 17 Python
解决python给列表里添加字典时被最后一个覆盖的问题
Jan 21 Python
Python整数对象实现原理详解
Jul 01 Python
代码实例讲解python3的编码问题
Jul 08 Python
Python中print函数简单使用总结
Aug 05 Python
解决python 文本过滤和清理问题
Aug 28 Python
PyQt5.6+pycharm配置以及pyinstaller生成exe(小白教程)
Jun 02 Python
PyCharm中配置PySide2的图文教程
Jun 18 Python
python3让print输出不换行的方法
Aug 24 Python
Python如何获取文件路径/目录
Sep 22 Python
python引入其他文件夹下的py文件具体方法
May 23 Python
python程序的组织结构详解
Dec 06 Python
[原创]教女朋友学Python3(二)简单的输入输出及内置函数查看
Nov 30 #Python
Python爬虫实现爬取京东手机页面的图片(实例代码)
Nov 30 #Python
Python编程使用tkinter模块实现计算器软件完整代码示例
Nov 29 #Python
Python科学画图代码分享
Nov 29 #Python
Python中Scrapy爬虫图片处理详解
Nov 29 #Python
Python使用django框架实现多人在线匿名聊天的小程序
Nov 29 #Python
Python实现的计数排序算法示例
Nov 29 #Python
You might like
在Windows中安装Apache2和PHP4的权威指南
2006/10/09 PHP
php实现36进制与10进制转换功能示例
2017/01/10 PHP
如何快速的呈现我们的网页的技巧整理
2007/07/01 Javascript
JavaScript 原型与继承说明
2010/06/09 Javascript
jquery中this的使用说明
2010/09/06 Javascript
js简单实现根据身份证号码识别性别年龄生日
2013/11/29 Javascript
LABjs、RequireJS、SeaJS的区别
2014/03/04 Javascript
JsRender for object语法简介
2014/10/31 Javascript
node.js中的http.response.setHeader方法使用说明
2014/12/14 Javascript
Bootstrap基本插件学习笔记之折叠(22)
2016/12/08 Javascript
ES6新特性:使用export和import实现模块化详解
2017/07/31 Javascript
Vue中跨域及打包部署到nginx跨域设置方法
2019/08/26 Javascript
vue远程加载sfc组件思路详解
2019/12/25 Javascript
mpvue网易云短信接口实现小程序短信登录的示例代码
2020/04/03 Javascript
vue中实现点击空白区域关闭弹窗的两种方法
2020/12/30 Vue.js
使用Python的Flask框架实现视频的流媒体传输
2015/03/31 Python
Python复制文件操作实例详解
2015/11/10 Python
python 请求服务器的实现代码(http请求和https请求)
2018/05/25 Python
python3 实现对图片进行局部切割的方法
2018/12/05 Python
利用python实现短信和电话提醒功能的例子
2019/08/08 Python
python 实现查询Neo4j多节点的多层关系
2019/12/23 Python
Python中如何添加自定义模块
2020/06/09 Python
scrapy redis配置文件setting参数详解
2020/11/18 Python
CSS类名支持中文命名的示例
2014/04/04 HTML / CSS
使用css如何制作时间ICON方法实践
2012/11/12 HTML / CSS
美国乡村商店:Plow & Hearth
2016/09/12 全球购物
纽约家具、家居装饰和地毯店:ABC Carpet & Home
2017/06/21 全球购物
国际礼品店:GiftsnIdeas
2018/05/03 全球购物
ETO男装官方网店:ETO Jeans
2019/02/28 全球购物
英国最好的包装供应商:Priory Direct
2019/12/17 全球购物
敬老文明号事迹材料
2014/01/16 职场文书
素质教育标语
2014/06/27 职场文书
民事诉讼代理词
2015/05/25 职场文书
2015年学校团委工作总结
2015/05/26 职场文书
员工工作失职检讨书范文!
2019/07/03 职场文书
Python探索生命起源 matplotlib细胞自动机动画演示
2022/04/21 Python