本文實例講述了Python實現按特定格式對文件進行讀寫的方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
#! /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 |
寫入的文件:
每一行的數據之間其實已經加入空格。
運行結果:
1
2
3
4
5
6
7
|
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程序設計有所幫助。
原文鏈接:http://blog.csdn.net/will130/article/details/50478481