Python實現(xiàn)按特定格式對文件進(jì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)文章
Pandas如何對帶有Multi-column(多列名稱)的數(shù)據(jù)排序并寫入Excel中
這篇文章主要介紹了Pandas如何對帶有Multi-column(多列名稱)的數(shù)據(jù)排序并寫入Excel中問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-02-02Python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)線性鏈表(單鏈表)算法示例
這篇文章主要介紹了Python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)線性鏈表(單鏈表)算法,結(jié)合實例形式分析了Python單鏈表的定義、節(jié)點插入、刪除、打印等相關(guān)操作技巧,需要的朋友可以參考下2019-05-05Python開發(fā)游戲之井字游戲的實戰(zhàn)步驟
最近正在學(xué)習(xí)Python,所以最近做了一個關(guān)于Python的實例,下面這篇文章主要給大家介紹了關(guān)于Python開發(fā)游戲之井字游戲的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02