Smooth python and cookbook Study Notes (7), pythoncookbook
1. Read and Write compressed data files
Use the gzip and bz2 modules to read and write compressed files. However, pay attention to the file mode. The default format is binary.
1 # Read the compressed file 2 import gzip 3 with gzip.open('somefile.gz ', 'rt') as f: 4 text = f. read () 5 6 import bz2 7 with bz2.open('somefile.bz2 ', 'rt') as f: 8 text = f. read () 9 10 # Write compressed data 11 import gzip12 with gzip.open('somefile.gz ', 'wt') as f: 13 f. write (text) 14 15 import bz216 with bz2.open('somefile.bz2 ', 'wt') as f: 17 f. write (text)
2. serialize Python objects
Use the pickle module to serialize data.
1. Transfer Data
>>> Import pickle >>> data = 'I love python' >>> f = open ('somefile', 'wb') >>> pickle. dump (data, f) # note that one is dump and the other is dumps> s = pickle. dumps (data)
2. Create an object from the byte stream and use the pickle. load () or pickle. loads () function.
>>> F = open ('somefile', 'B') >>> data = pickle. load (f) >>> data = pickle. loads (f)