1. 程式人生 > >python程序設計——文件操作

python程序設計——文件操作

txt load 模塊 use 關閉 過程 RM 文件操作 except

分類

1.文本文件

存儲常規字符串,由若幹文本行組成,每行以換行符‘\n‘結尾

2.二進制文件

把對象以字節串存儲,常見的圖形圖像、可執行文件、數據庫文件office文檔等

 1 #創建文件
 2 >>fw = open(sample.txt,w+,encoding=utf-8)
 3 >>s = 文本讀取方式\n sample.txt w+\n
 4 >>fw.write(s)
 5 >>fw.close()
 6 #查看sample.txt
 7 文本讀取方式
 8  sample.txt w+
 9 
10 #建議形式,關鍵字with可以自動管理資源
11 >>s = 文本讀取方式\n sample.txt w+\n 12 >>with open(sample.txt,w+,encoding=utf-8) as fw: 13 >> fw.write(s) 14 # 判斷文件對象是否關閉 15 >>fw.colsed 16 True 17 18 #添加文件內容 19 >>s = hello\n 20 >>with open(sample.txt,a+,encoding=utf-8) as fa: 21 >> fa.write(s)
22 文本讀取方式 23 sample.txt w+ 24 hello 25 26 # 讀取文件內容 27 # 讀取一行 28 >>fread = open(sample.txt,r,encoding=utf-8) 29 >>fread.readline() 30 文本讀取方式\n 31 >>fread.readline() 32 sample.txt w+\n 33 >>fread.readline() 34 hello\n 35 36 # 一次讀取所有行 37 >>fread = open(sample.txt
,r,encoding=utf-8) 38 >>fread.readlines() 39 [文本讀取方式\n, sample.txt w+\n, hello\n] 40 41 #讀取固定字符個數 42 >>fread = open(sample.txt,r,encoding=utf-8) 43 >>fread.read(4) 44 文本讀取
45 >>fread.close()

可以使用dir() 查看與對象相關的方法,使用help()查看方法的用法

1 >>fread = open(sample.txt,r,encoding=utf-8)
2 >>fread.colse()
3 >>dir(fread)
4 #查看read()函數用法
5 >>help(fread.read)

文件序列化

序列化,就是把內存中的數據在不丟失數據類型的情況下,轉化為二進制形式的過程

1.使用pickle模塊

Pickle是常用並且快速的二進制文件序列化模塊

 1 #使用pickle dump依次寫入二進制文件
 2 import pickle
 3 f = open(sample_pickle.dat,wb)
 4 
 5 alist = [[2,3,4],[6,7,8]]
 6 aset = {a,b,c}
 7 atuple = (-5,-3,-1)
 8 astr = 北京歡迎你,welcome!
 9 adic = {name:jin,sex:None}
10 try:
11     pickle.dump(alist,f)
12     pickle.dump(aset,f)
13     pickle.dump(atuple,f)
14     pickle.dump(astr,f)
15     pickle.dump(adic,f)
16 except:
17     print(write error)
18 finally:
19     f.close()
20 
21 #使用Pickle load依次讀取二進制文件
22 fr = open(sample_pickle.dat,rb)
23 try:
24     x=pickle.load(fr)
25     print(x)
26     x=pickle.load(fr)
27     print(x)
28     x=pickle.load(fr)
29     print(x)
30     x=pickle.load(fr)
31     print(x)
32     x=pickle.load(fr)
33     print(x)
34 except:
35     print(read error)
36 finally:
37     fr.close()

2.使用struct模塊

 1 import struct
 2 import binascii
 3  
 4 values = (1, bgood, 1.22) #字符串必須為字節流類型
 5 s = struct.Struct(I4sf)
 6 packed_data = s.pack(*values) #序列解包
 7 unpacked_data = s.unpack(packed_data)
 8   
 9 print(Original values:, values)
10 print(Format string :, s.format)
11 print(Uses :, s.size, bytes)
12 print(Packed Value :, binascii.hexlify(packed_data))
13 print(Unpacked Type :, type(unpacked_data),  Value:, unpacked_data)
14 
15 out:
16 Original values: (1, bgood, 1.22)
17 Format string : bI4sf
18 Uses : 12 bytes
19 Packed Value : b01000000676f6f64f6289c3f
20 Unpacked Type : <class tuple>  Value: (1, bgood, 1.2200000286102295)

python程序設計——文件操作