7.4 二进制文件操作 数据库文件、图像文件、可执行文件、音频视频文件等等均属于二进制文件。 对于二进制文件,不能使用记事本或其他文本编辑软件进行正常读写。 7.4.1 使用struct模块 例:使用struct模块写入二进制文件: import struct n=1300000000 x=96.45 b=True s='a1@中国' sn=struct.pack('if?', n, x, b) #把整数n、浮点数x、布尔对象b依次转换为字节串 f=open('sample_struct.dat', 'wb') f.write(sn) #写入字节串 f.write(s) #字符串可直接写入 f.close( ) 7.4.1 使用struct模块 例:使用struct模块读取二进制文件。 import struct f=open('sample_struct.dat', 'rb') sn=f.read(9) tu=struct.unpack('if?', sn) #从字节串sn中还原出1个整数、1个浮点数和1个布尔值,并返回元组 print(tu) n=tu[0] x=tu[1] bl=tu[2] print 'n=', n print 'x=', x print 'bl=', bl s=f.read(9) f.close() print 's=', s 7.4.2 使用pickle模块 写入文件: import pickle f=open('sample_pickle..dat', 'wb') n=7 ia=99.056 s='中国人民123abc' lst=[[1, 2, 3], [4, 5, 6], [7, 8, 9]] tu=(-5, 10, 8) coll={4, 5, 6} dic={'a':'apple', 'b':'banana', 'g':'grape', 'o':'orange'} try: pickle.dump(n, f) #表示后面将要写入的数据个数 pickle.dump(i, f) #把整数i转换为字节串,并写入文件 pickle.dump(a, f) pickle.dump(s, f) pickle.dump(lst, f) pickle.dump(tu, f) pickle.dump(coll, f) pickle.dump(dic, f) except: print '写文件异常!' #如果写文件异常则跳到此处执行 f.close( ) 7.4.2 使用pickle模块 读取二进制文件: import pickle f=open('sample_pickle.dat', 'rb') n = pickle.load(f) #读出文件的数据个数 i=0 while i>> import os >>
python文件的读写ppt,Python程序设计-文件操作.ppt
最新推荐文章于 2023-08-08 09:22:42 发布