注:load后不影响持久化文件;F.write(str),把str写到文件F中,write()并不会在str后加一个换行符。
执行结果:
pickle_sample.txt如下:
write_sample.txt如下:
#!/usr/bin/env python#-*- coding: utf-8 -*-import cPickle as pickleimport randomimport osimport timeLength = 100 * 1000print "Length is %d" %Lengthdef main(): d = {} a = [] for i in range(Length): a.append(random.randint(0, 255)) d["a"] = a #print "d is %s" %d #print "a is %s" %a print "dumping..." #time.time()时间戳,返回从1970/01/01以来的秒数,这是一个浮点数 t1 = time.time() #wb 以二进制写模式打开 pickle.dump(d, open("tmp1.dat", "wb"), True) print "tmp1 dump1: %.3fs" %(time.time() - t1) t1 = time.time() #w 以写方式打开 pickle.dump(d, open("tmp2.dat", "w")) print "tmp2 dump2: %.3fs" %(time.time() - t1) t1 = time.time() open("tmp3.dat", "wb").write("%s" %d) print "tmp3 write1: %.3fs" %(time.time() - t1) s1= os.stat("tmp1.dat").st_size s2= os.stat("tmp2.dat").st_size s3= os.stat("tmp3.dat").st_size #%%百分号标记 print "tmp1.size is %d, tmp2.size is %d, tmp3.size is %d, tmp1.size/tmp2.size is %.2f%%" %(s1, s2, s3, 100.0 * s1/s2) print "loading..." t1 = time.time() #rb 以二进制读模式打开 obj1 = pickle.load(open("tmp1.dat", "rb")) print "tmp1 load1: %.3fs" %(time.time() - t1) t1 = time.time() #r 以读模式打开 obj2 = pickle.load(open("tmp2.dat", "r")) print "tmp2 load2: %.3fs" %(time.time() - t1) t1 = time.time() f = open("tmp3.dat", "r") print "tmp3 open: %.3fs" %(time.time() - t1) f.close()if __name__ == "__main__": main()
输出: