欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python實現(xiàn)按特定格式對文件進(jìn)行讀寫的方法示例

 更新時間:2017年11月30日 11:27:57   作者:愛橙子的OK繃  
這篇文章主要介紹了Python實現(xiàn)按特定格式對文件進(jìn)行讀寫的方法,可實現(xiàn)文件按原有格式讀取與寫入的功能,涉及文件的讀取、遍歷、轉(zhuǎn)換、寫入等相關(guān)操作技巧,需要的朋友可以參考下

本文實例講述了Python實現(xiàn)按特定格式對文件進(jìn)行讀寫的方法。分享給大家供大家參考,具體如下:

#! /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()#讀取出全部數(shù)據(jù),按行存儲
    finally:
      fp.close()
    for line in lines:
      dict = {}
      #print line.split() #like['compute21', '2', '4']
      line_list = line.split() #默認(rèn)以空格為分隔符對字符串進(jìn)行切片
      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、寫入數(shù)據(jù)
  #print 'write start!'
  file_handle.WriteFile()
  #print 'write finish!'
  #2、讀取數(shù)據(jù)
  res = file_handle.ReadFile()
  print res

寫入的文件:

每一行的數(shù)據(jù)之間其實已經(jīng)加入空格。

運行結(jié)果:

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}]

實現(xiàn)了按原有格式寫入和讀取。

更多關(guān)于Python相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Python編碼操作技巧總結(jié)》、《Python圖片操作技巧總結(jié)》、《Python數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Python Socket編程技巧總結(jié)》、《Python函數(shù)使用技巧總結(jié)》、《Python字符串操作技巧匯總》、《Python入門與進(jìn)階經(jīng)典教程》及《Python文件與目錄操作技巧匯總

希望本文所述對大家Python程序設(shè)計有所幫助。

相關(guān)文章

最新評論