代码如下:
#encoding=utf-8 print '中国' #固定长度的二进制文件,读取某些记录修改,然后写回去 '''d:\123.txt的内容 1 a b c 中 国 2 a b c 中 国 ''' import struct format_string = '2c' #一个记录是2个字节 record_size = struct.calcsize(format_string) record_number=2 thefile = open(r'd:\123.txt','rb+') thefile.seek(record_size *record_number) buffer = thefile.read(record_size) print buffer fields = list(struct.unpack(format_string,buffer)) print '--fields' print fields fields[0] = 'c' buffer = struct.pack(format_string,*fields) thefile.seek(record_size *record_number) thefile.write(buffer) thefile.close() #文件中内容变为 ''' 1 a c c 中 国 2 a b c 中 国 '''
打印结果如下:
中国
b
--fields
['b', ' ']