首页 > 编程语言 > 详细

Python语言之持久化

时间:2020-01-07 00:43:44      阅读:98      评论:0      收藏:0      [点我收藏+]

(一)扁平文件

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()

Python语言之持久化

原文:https://www.cnblogs.com/gdy1993/p/12158770.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!