iT邦幫忙

0

python json寫檔和讀檔的問題~

  • 分享至 

  • xImage

我用python 寫一個寫入檔案跟讀檔的程式
程式碼如下

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)
     12 
~\AppData\Local\Temp/ipykernel_2220/379544952.py in add_password(name, account, password)
      3     with open('account.json','w') as file:
      4 
----> 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())
      4 
~\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)
    335 
    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)

請問我該如何解決

我打錯了import json
我原本打在最上方
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
熊熊工程師
iT邦研究生 1 級 ‧ 2022-10-29 16:18:45
最佳解答

不可以在 w 權限內又對同個檔案用 with 進行開啟,要把它分開

import json

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)

感謝大大的回覆 ,另外可以在問一個問題嗎?
with open("檔案",r) as file: file.read()
是不適只能有一個.read() 如果有重複則不執行呢>

我要發表回答

立即登入回答