添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
程式碼如下

with open('account.json','w') as file:
    file.write(json.dumps({'google':{'a123':'123'}}))
import json
def get_password_dic():
    with open('account.json','r',encoding='utf-8') as file:
        x = json.loads(file.read())
    return x
def add_password(name,account,password):
    with open('account.json','w',encoding='utf-8') as file:
        password_dic = get_password_dic()
        password_dic[name] = {
            "account":account,
            "password":password
        file.write(json.dumps(password_dic))
print("歡迎來到密碼管理器~")
while True:
    mode = input("請輸入你想要(a新增 r讀取 q離開): ")
    if mode == "q":
        break
    elif mode == "a":
        name = input("請輸入你要新增的帳號名稱: ")
        account = input("請輸入帳號: ")
        password = input("請輸入密碼: ")
        add_password(name,account,password)

結果出現抱錯

JSONDecodeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_2220/894925555.py in <module> 9 account = input("請輸入帳號: ") 10 password = input("請輸入密碼: ") ---> 11 add_password(name,account,password) ~\AppData\Local\Temp/ipykernel_2220/379544952.py in add_password(name, account, password) 3 with open('account.json','w') as file: ----> 5 password_dic = get_password_dic() 6 password_dic[name] = { 7 "account":account, ~\AppData\Local\Temp/ipykernel_2220/3290210138.py in get_password_dic() 1 def get_password_dic(): 2 with open('account.json','r') as file: ----> 3 return json.loads(file.read()) ~\Anaconda3\lib\json\__init__.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw) 344 parse_int is None and parse_float is None and 345 parse_constant is None and object_pairs_hook is None and not kw): --> 346 return _default_decoder.decode(s) 347 if cls is None: 348 cls = JSONDecoder ~\Anaconda3\lib\json\decoder.py in decode(self, s, _w) 336 """ --> 337 obj, end = self.raw_decode(s, idx=_w(s, 0).end()) 338 end = _w(s, end).end() 339 if end != len(s): ~\Anaconda3\lib\json\decoder.py in raw_decode(self, s, idx) 353 obj, end = self.scan_once(s, idx) 354 except StopIteration as err: --> 355 raise JSONDecodeError("Expecting value", s, err.value) from None 356 return obj, end JSONDecodeError: Expecting value: line 1 column 1 (char 0)

請問我該如何解決

with open('account.json', 'w') as file: file.write(json.dumps({'google': {'a123': '123'}})) def get_password_dic(): with open('account.json', 'r', encoding='utf-8') as file: x = json.loads(file.read()) return x def add_password(name, account, password): password_dic = get_password_dic() with open('account.json', 'w', encoding='utf-8') as file: password_dic[name] = { "account": account, "password": password file.write(json.dumps(password_dic)) print("歡迎來到密碼管理器~") while True: mode = input("請輸入你想要(a新增 r讀取 q離開): ") if mode == "q": break elif mode == "a": name = input("請輸入你要新增的帳號名稱: ") account = input("請輸入帳號: ") password = input("請輸入密碼: ") add_password(name, account, password)