2011-07-28 3 views
1

cPickle을 사용하여 개체를 저장하고 있습니다. 나중에 개인 기록을 수정하고 싶습니다.Python : 절인 된 개체 수정

만들고 피클

class Book(object): 
    def __init__(self, title, author, ISBN, price): 
     self.title = title 
     self.author = author 
     self.ISBN = ISBN 
     self.price = price 

def main(): 
    from cPickle import dump 
    from random import choice 
    from random import randrange 
    letters = ("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", 
      "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", 
      "w", "x", "y", "z") 
    f = open("books.dat", "a+b") 

    for ctr in range(0, 20): 
     title = "" 
     author = "" 
     ISBN = "" 
     price = randrange(20,100) 
     for i in range(10): 
      title+=choice(letters) 
      author+=choice(letters) 
      ISBN+=str(randrange(0,14)) 
     book = Book(title, author, ISBN, price) 
     # writing structure 
     dump(book, f) 
    f.close() 
    print "Finished." 

main() 

unPickle 및

class Book(object): 
    def __init__(self, title, author, ISBN, price): 
     self.title = title 
     self.author = author 
     self.ISBN = ISBN 
     self.price = price 

    def __str__(self): 
     rep = self.title+" by "+self.author+".\n" 
     rep += "ISBN: "+self.ISBN+"\n" 
     rep += "Price: "+str(self.price) 
     return rep 

def main(): 
    from cPickle import load 
    from cPickle import dump 
    import sys 

    books = [] 
    EOF = False 
    f = open("books.dat", "r+b") 
    print "Loading..." 
    while not EOF: 
     try: 
      book = load(f) 
     except(EOFError): 
      EOF = True 
     else: 
      books.append(book) 
    print "Load complete." 
    rec = int(raw_input("Record to delete: ")) 
    print books[rec] 
    fwd = 0 
    for i in range(rec): 
     fwd+= sys.getsizeof(books[i]) 
    print str(fwd) 
    title = "New" 
    author = "New" 
    ISBN = "New" 
    price = 0 
    new = Book(title, author, ISBN, price) 
    print str(sys.getsizeof(new)) 
    f.seek(fwd) 
    dump(new, f) 
    f.close() 

main() 
+0

정확한 오류가 무엇입니까 : 즉

는 다음과 같은 시도? 어쨌든, 지금 내장 된 sqlite3 모듈을 사용해보십시오. 또한 실제 데이터베이스에 대한 마이그레이션 경로를 제공해야합니다. – Keith

+0

역 추적 (마지막으로 가장 최근 통화) : 파일 "/Users/aed0101/Dropbox/QSAP/cPickle/unpack.py", 라인 49, 주() 파일에서 "/ 사용자/aed0101/보관/QSAP /의 cPickle /unpack.py ", 27 행, 주 book = load (f) UnpicklingError : 잘못된로드 키 '_'. – aeed0101

+0

나는 sqlite3을 시도했다. 그것을 사용할 것입니다. 고맙습니다! – aeed0101

답변

2

나는 확실하지 않다 수정하지만 이후 나에게 보인다 불행하게도 파일이 (내가 UnpicklingError을 얻고있다) 수정 후 손상지고 이 목록의 컨텍스트로 파일을 다시 작성하면 쉽고 오류가 없기 때문에 이미 책 객체 목록 (파일에서로드 됨)이 있습니다 (원하는 레코드를 제거하거나 books [i] = new) 대신 덤프를 사용하여 plave를 찾으려고 시도합니다. 여기서 t o 새 기록을 삽입하십시오.

class Book(object): 

    def __init__(self, title, author, ISBN, price): 
     self.title = title 
     self.author = author 
     self.ISBN = ISBN 
     self.price = price 

    def __str__(self): 
     rep = self.title+" by "+self.author+".\n" 
     rep += "ISBN: "+self.ISBN+"\n" 
     rep += "Price: "+str(self.price) 
     return rep 

def main(): 
    from cPickle import load, dump 

    print "Loading..." 
    books = [load(line) for line in open("books.dat", "rb")] 
    print "Load complete." 

    rec = int(raw_input("Record to delete: "))   
    title = "New" 
    author = "New" 
    ISBN = "New" 
    price = 0 

    books[rec] = Book(title, author, ISBN, price) # replace previous record 

    with open("books.dat", "wb") as f:   
     for record in books: 
      dump(record, f) 


main() 
+0

감사합니다. 나는 덮어 쓰지 않고 그것을하려고 노력했다. getsizeof가 올바른 크기를보고하지 않는 것 같습니다. – aeed0101

+0

@ aeed0101 - seek, getsizeof 등을 사용하면이 경우에 도움이 될지 확실하지 않습니다. –

+0

len이 0 인 도서를 가정 해 보겠습니다. – gath