• 第十二天:对象持久化


    一、扁平文件

    • 文本文件
    scores = [88, 99, 77, 55]
    def write_scores():
        with open('datafile.txt', 'w', encoding = 'utf8') as f: #文件仅含一个列表
            f.write(str(scores))
        print('文件写入完成...')
    def read_scores():
        with open('datafile.txt', 'r', encoding='utf8') as f:
            lst = eval(f.read()) #转换数据类型        
        lst[0] = 99
        print(lst)
    if __name__ == '__main__':
        #write_scores() #先运行写入函数
        read_scores()
    
    [99, 99, 77, 55]
    

    二、pickle

    1、序列化为字符串

    • 将对象序列化为字符串 pickle.dumps(obj)
    • 从字符串反序列化为对象 pickle.loads(s)
    import pickle
    person = {'name':'Tom', 'age':20}
    s = pickle.dumps(person) #把任意类型对象序列化成字符串
    s
    p = pickle.loads(s) #反向转换
    p
    
    b'x80x03}qx00(Xx04x00x00x00nameqx01Xx03x00x00x00Tomqx02Xx03x00x00x00ageqx03Kx14u.'
    {'name': 'Tom', 'age': 20}
    

    2、序列化对象到文件

    • 对象序列化为文件 pickle.dump(obj, file)
    • 文件反序列化为对象 pickle.load(file)
    pickle.dump(person, open('pickle_db', 'wb'))
    p = pickle.load(open('pickle_db', 'rb'))
    p
    type(p)
    
    {'name': 'Tom', 'age': 20}
    dict
    

    三、shelve

    • .open('dbfile')
    • .close()
    • db['key']=obj
    • len(db)
    import shelve
    scores = [99, 88, 77]
    student = {'name':'Mike', 'age':20}
    db = shelve.open('shelve_student') #创建数据库文件
    db['s'] = student
    db['scores'] = scores
    len(db) #有两个键值
    temp_student = db['s']
    temp_student
    type(temp_student)
    
    2
    {'name': 'Mike', 'age': 20}
    dict
    
    • del db['key']
    del db['scores']
    len(db)
    
    1
    
    class Student:
        def __init__(self, name, age):
            self.name = name 
            self.age = age
        def __str__(self):
            return self.name
    def write_shelve():
            s = Student('Yom', 20)
            db = shelve.open('shelve_student_db')
            db['s'] = s
            db.close()
    def read_shelve():
        db = shelve.open('shelve_student_db')
        st = db['s']
        print(st)
        print(st.name)
        print(st.age)
        db.close()
    if __name__ == '__main__':
        #write_shelve() #先写入再读取
        read_shelve()
    
    Yom
    Yom
    20
    
  • 相关阅读:
    Java中的toString、equals方法覆写,懒汉式单例模式,及异常处理
    【Java】String类、Object类、包装类总结
    Java接口练习
    Java面向对象测试
    【Java】二叉搜索树的实现操作及应用
    【Java】实现二叉树基本操作、面试题
    SAS--宏变量
    SAS--array
    SAS--do loop until while
    SAS--设置行号、标记
  • 原文地址:https://www.cnblogs.com/linyk/p/11483401.html
Copyright © 2020-2023  润新知