简体   繁体   中英

Python remove entry from pickle saved data

Firstly, I am aware of this post which state that i have to rewrite the whole file in order for me to delete away 1 item from pickle saved data.

I have a file which keeps the username and password(password's hash value) in binary form.It is created by this code:

import pickle
import hashlib

def Encryption(data):
    return hashlib.sha224(data).hexdigest()

db = {'user1' : Encryption('password1'), 'user2' : Encryption('password2'), 'user3' : Encryption('password3')}
fh = open('database.db', 'wb')
pickle.dump(db, fh)
fh.close()

I want to remove user2,password2 (2nd entry) from the file. So this is what i did

import pickle
import hashlib
from os import path

n='user2'

def Encryption(data):
    return hashlib.sha224(data).hexdigest()

if path.isfile('database.db'):
    fh=open('database.db','rb')
    db=pickle.load(fh)
    fh.close()

_newlist,_newlist2=([] for i in range (2))    
_username=[]
_password=[]

#Get the user names and passwords hash values into two different list
for user in db:
    _username.append(user)
    _password.append(db[user])    

#If user name is equal to the user name i want to delete, skip . Else append it to new list
for i in range(len(_username)):
    if n==_username[i]:
        pass
    else:
        _newlist.append(_username[i])
        _newlist2.append(_password[i])

#Clear the file
fh=open('database.db','wb')
fh.close()

#Re-write the new lists to the file
for i in range(len(_newlist)):
    db={_newlist[i]:_newlist2[i]}
    fh = open('database.db', 'ab')
    pickle.dump(db,fh)

Instead of removing the 2nd entry(user2,password2), it removes all but last entry. Colud anyone help me point out what's wrong in my code?

You can store the users and passwords using one dictionary and just remove the "user-to-delete" from that dictionary.

import pickle
from os import path

user_to_delete = 'user2'

# Open the database if it exists, otherwise create one...
if path.isfile('database.db'):
    with open('database.db','rb') as f:
        db = pickle.load(f)
else: # Create some database.db with users&passwords to test this program..
    db = {'user1':'password1', 'user2':'password2', 'user3':'password3'}
    with open('database.db', 'wb') as f:
        pickle.dump(db, f)

# try to delete the given user, handle if the user doesn't exist.
try:
    del db[user_to_delete]
except KeyError:
    print("{user} doesn't exist in db".format(user=user_to_delete))

# write the 'new' db to the file.
with open('database.db', 'wb') as f:
    pickle.dump(db, f)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM