我想將包含用戶資訊的字典放入一個新的 json 檔案中,并且我希望它在我呼叫函式“new_user”時給每個用戶一個數字。我該怎么做?
from get_stars import rate_service
user_info = {
'user_number': int(),
'user_info': {
'username': 'username',
'user_location': 'user_location',
'used_application': 'used_application',
'stars': int()
}
}
def get_user_info():
new_user = user_info.copy()
new_user['user_info']['username'] = input(f"\nEnter your name: ")
new_user['user_info']['stars'] = rate_service()
return new_user
from userinfo import get_user_info
import json
def new_user():
user = get_user_info()
filename = f"user.json"
with open(filename, 'w'):
json.dump(filename, user)
例如,我呼叫該 func 并且在我的 json 檔案中有用戶編號為 1 的 dict,但是當我下次呼叫它時,這個數字會增加 1
uj5u.com熱心網友回復:
如果您想在分配編號之前避免讀取檔案,我將使用 Guuid,這基本上是一個亂數,如此之大,完全可以保證不會與其他人發生沖突。
如果你想分配一個整數,那么你有兩個選擇:
- 在設定用戶資訊之前讀取取最大值并分配的檔案
- 擁有另一個檔案,其中包含您還將閱讀的用戶計數的“元資料”。
通常這種操作是使用資料庫來完成的。
您還可以使用索引資料框、數字字典甚至用戶串列作為中間資料結構,如果您選擇選項 1,它將為您提供幫助。
uj5u.com熱心網友回復:
分配一個 uuid:https ://docs.python.org/3/library/uuid.html
import uuid
new_user = {}
new_user['user_number'] = uuid.uuid1()
# output: {'user_number': UUID('d2586590-abb8-11ec-94de-acde48001122')}
print(new_user)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/451095.html
