码迷,mamicode.com
首页 > 编程语言 > 详细

Python语言之持久化

时间:2020-01-06 22:30:51      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:encoding   write   import   cores   port   eval   python语言   --   print   

(一)扁平文件

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语言之持久化

标签:encoding   write   import   cores   port   eval   python语言   --   print   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!