[英]AttributeError: 'dict' object has no attribute 'append' in json
[英]AttributeError: 'dict' object has no attribute 'append' Trying to write to .JSON file
我有一個腳本,我試圖寫入一個名為alerts_comments.json的.JSON文件我在Windows上工作,但當我將它移動到Ubuntu時,我收到標題中的錯誤。 我對此很新,而且有點卡住了。 我知道這是列表和詞典的問題,但我無法弄清楚。 任何幫助,將不勝感激
我在Ubuntu上使用python 3.6。
我目前與此問題相關的代碼就在這里。
with open(save_path, 'r') as fp:
alerted_comments = json.load(fp)
for comment in comment_stream:
if comment.id in alerted_comments:
continue
if comment.author: # if comment author hasn't deleted
if comment.author.name in ignore_users:
continue
alerted_comments.append(comment.id)
if len(alerted_comments) > 100:
alerted_comments = alerted_comments[-100:]
with open(save_path, 'w') as fp:
json.dump(alerted_comments, fp)
else:
# You'll probably want to be more discerning than "not 200",
# but that's fine for now.
raise SlackError('Request to Slack returned an error %s, the response is:\n%s' % (response.status_code, response.text))
if __name__ == '__main__':
while True:
try:
main(save_path='alerted_comments.json')
except Exception as e:
print('There was an error: {}'.format(str(e)))
time.sleep(60) # wait for 60 seconds before restarting
意味着要發生的是,腳本讀取一個關鍵字,然后將該關鍵字的注釋id放入alerts_comments.json中,以便它記住並且不再重復相同的關鍵字。
從錯誤中我們可以發現,當假設list
時我們正在使用dict
實例,因此問題在於傳遞JSON或我們關於其結構的假設。
從對話中可以看出,初始JSON具有
{}
在其內容中使用空對象文字,在使用json.load
進行反序列化后成為Python dict
,所以如果它應該是一個空數組,我們可以用
[]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.