Python 언어의 지속성

1702 단어
카탈로그
  • (一) 편평한 파일
  • (2)pickle
  • (3)shelve

  • (1) 납작한 파일

    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]

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

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

    좋은 웹페이지 즐겨찾기