[英]Python remove entry from pickle saved data
首先,我知道該帖子指出哪個狀態,我必須重寫整個文件 ,才能從泡菜保存的數據中刪除1個項目。
我有一個文件,以二進制形式保存用戶名和密碼(密碼的哈希值),它是由以下代碼創建的:
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()
我想從文件中刪除user2,password2
(第二項)。 這就是我所做的
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)
而不是刪除第二個條目(user2,password2),它會刪除除最后一個條目以外的所有條目。 Colud有人幫我指出我的代碼有什么問題嗎?
您可以使用一個字典來存儲用戶和密碼,只需從該字典中刪除“刪除用戶”即可。
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.