Я читаю / записываю в текстовый файл, используя python 'с открытым (и т. Д.) Как файл'
По какой-то причине у меня возникают проблемы с неправильным сохранением файла.Переменная с именем 'Hash_Table' обновляется и изменяется в операторе with, а затем, наконец, сохраняется после усечения остальной части файла.Несмотря на это, по-видимому, возникают проблемы с поиском этих изменений после.
Я попытался сделать так, чтобы все функции, которые имеют дело с хеш-таблицей, содержались в отдельном операторе «with», функции, вызываемые внутрис оператором
"""This snippet is designed to simply add a user to the hash table, this
does not work"""
with open("HashTable.txt", "r+") as File:
Hash_Table = json.load(File)
print("Loaded")
Hash_Table,Continue_A = self.Add_User_Hash(User_Data[:2],Hash_Table)
print("Done")
if Continue_A:
print("Yayyy")
File.seek(0)
File.truncate()
print("truncated")
json.dump(Hash_Table, File)
self.Data_Handler.Send_Q.put(Continue_A) # Tells client result of function
"""Here is a snippet from a called function.
I am unsure of whether this works because the previous snippet does not
work properly, this snippet aims to delete a user, then add it back
with new details"""
successfully add the user
with open("HashTable.txt", "r+") as File:
Hash_Table = json.load(File)
Hash_Table, Completed_R = self.Remove_User_Hash((Orig_Details["Username"], Orig_Details["Password"]),Hash_Table)
if Completed_R:
# If deletion is successful, add the user to the database
Hash_Table, Completed_A = self.Add_User_Hash((New_Details["Username"], New_Details["Password"]),Hash_Table)
if Completed_A:
File.seek(0)
File.truncate()
json.dump(Hash_Table,File)
else:
Error_Report("Deletion gone wrong","Edit_User_Handler")
def Remove_User_Hash(self, User_Details,Hash_Table):
print("delete hash")
print("User_Details:",User_Details)
Deleted = False
Hash_ID = self.Get_Hash_ID(User_Details) # Gets the hash ID
print("Hash_ID:",Hash_ID)
Count = 0
print("Hash_Table:",Hash_Table)
# Decodes json object into a dictionary
while Count <= HASH_KEY and not Deleted:
# While count is less than the table size
#try:
print("Hash_Tab_ID:",Hash_Table[str(Hash_ID)])
print("User_Details:",list(User_Details))
if Hash_Table[str(Hash_ID)] == list(User_Details):
# Checks if given information matches the data relating to the key
del Hash_Table[str(Hash_ID)] # Delete the entry
Deleted = True
else:
Hash_ID += 1
# Increments Hash_ID by one if the key is already occupied but does not match search details
Count += 1 # Increments Count by one
if Deleted: # If the user has been deleted
Continue_A = False
time.sleep(0.5)
print("After Write")
print("Hash_Table var :",Hash_Table)
Temp_Hash_Table = {}
"""This resets all the Users and their hash table positions in
the database (Removes incrementation where applicable)"""
for i in Hash_Table: # Replace all values in the file (hash_table) with all non-deleted users
Temp_Hash_Table, Continue_A = self.Add_User_Hash(Hash_Table[i],Temp_Hash_Table)
return Hash_Table, Continue_A
# Tells the called from function that the user was / was not deleted
else:
return Hash_Table,False
# Tells called from function that the user was not deleted if count ever reaches a value greater than HASH_KEY
def Add_User_Hash(self, User_Data, Hash_Table):
print("User_Data_Hash:",User_Data)
Hash_ID = self.Get_Hash_ID(User_Data) # Gets hash id
with global_lock: # Loads json object of hash table # Loads hash table from json object
count = 0
while count <= HASH_KEY and Hash_Table:
# While the user hasn't been added to the DB and the count is less than the table size
count += 1 # Count is used to make sure the algorithm has a stop condition if no places are available
if Hash_ID >= HASH_KEY: # If Hash_ID is greater than or equal to the table size, set Hash_ID to zero
Hash_ID = 0
if str(Hash_ID) in Hash_Table:
# If this key is occupied, increment the value of Hash_ID by one
Hash_ID += 1
else: # Add new value to hash table if it doesn't already exist
Hash_Table[str(Hash_ID)] = list(User_Data)
return Hash_Table,True
return Hash_Table,False
Я хочу, чтобы функция добавления пользователя добавляла пользователей в хеш-таблицу, а функция удаления пользователя - их удаление.И затем всякий раз, когда они вызываются, следует затем сохранить хеш-таблицу, используя json, в текстовый файл.Однако это не так.