Python 读写文件---pickle 二进制方式读写


initdata.py:

# initialize data to be stored in files, pickles, shelves

# records
bob = {'name': 'Bob Smith', 'age': 42, 'pay': 30000, 'job': 'dev'}
sue = {'name': 'Sue Jones', 'age': 45, 'pay': 40000, 'job': 'hdw'}
tom = {'name': 'Tom',       'age': 50, 'pay': 0,     'job': None}

# database
db = {}
db['bob'] = bob
db['sue'] = sue
db['tom'] = tom

if __name__ == '__main__':       # when run as a script
    for key in db:
        print(key, '=>\n  ', db[key])



make_db_pickle.py:

from initdata import db
import pickle
dbfile = open('people-pickle', 'wb')               # use binary mode files in 3.X
pickle.dump(db, dbfile)                            # data is bytes, not str
dbfile.close()


dump_db_pickle.py:

import pickle
dbfile = open('people-pickle', 'rb')               # use binary mode files in 3.X
db = pickle.load(dbfile)
for key in db:
    print(key, '=>\n  ', db[key])
print(db['sue']['name'])

update_db_pickle.py:

import pickle
dbfile = open('people-pickle', 'rb')
db = pickle.load(dbfile)
dbfile.close()

db['sue']['pay'] *= 1.10
db['tom']['name'] = 'Tom Tom'

dbfile = open('people-pickle', 'wb')
pickle.dump(db, dbfile)
dbfile.close()



你可能感兴趣的:(Python 读写文件---pickle 二进制方式读写)