Python语言之持久化

(一)扁平文件

scores = [88,99,77,55]


def write_scores():
    with open('date_list.txt','w',encoding='utf8') as f:
        f.write(str(scores))
    print('文件写入成功


def read_scores():
    with open('date_list.txt','r',encoding='utf8') as f:
        list = eval(f.read())
        list[0] = 87
        print(list)


if __name__ == '__main__':
    write_scores()
    read_scores()
----------------------------------------
文件写入成功!
[87, 99, 77, 55]

(二)pickle

>>> import pickle
>>> person = {'name':'Tom','age':20}
>>> s = pickle.dumps(person)
>>> s
b'\x80\x03}q\x00(X\x04\x00\x00\x00nameq\x01X\x03\x00\x00\x00Tomq\x02X\x03\x00\x00\x00ageq\x03K\x14u.'
>>> p = pickle.loads(s)
>>> p
{'name': 'Tom', 'age': 20}
>>> pickle.dump(person,open('pickle_dump','wb'))
>>> p = pickle.load(open('pickle_dump','rb'))
>>> p
{'name': 'Tom', 'age': 20}

(三)shelve

import shelve

# scores = [99,88,77]
# student = {'name':'Tom','age':20}
# db = shelve.open('shelve_student')
# db['s'] = student
# db['scores'] = scores
# print(len(db))
db = shelve.open('shelve_student')
stu = db['s']
print(stu)
scores = db['scores']
print(scores)
#删除
del db['s']
db.close()
posted @ 2020-01-06 22:04  sowhat1943  阅读(126)  评论(0编辑  收藏  举报