【问题标题】:Append in a list [Python]追加到列表中 [Python]
【发布时间】:2021-01-09 20:03:50
【问题描述】:

有人可以向我解释为什么我会收到此错误消息:

第 27 行,在 liste_de_courses.append(item_add)

AttributeError: 'str' object has no attribute 'append

提前感谢您的帮助

import os
import json

dossier_courant = os.path.dirname(__file__)

dossier = os.path.join (dossier_courant, "liste.json")

if os.path.exists(dossier):
    with open (dossier, "r") as f:
        liste_de_courses = json.load(f)
else:
    liste_de_courses = []

affichage = """
\t1: Add a item
\t2: Delete a item
\t3: Show a item
\t4: Empty a item
\t5: Over
"""
choix_utilisateur = "0"
while choix_utilisateur != "5":

    choix_utilisateur = input (affichage)
    if choix_utilisateur == "1":
        item_add = input ("What would you like to add ? ")
        liste_de_courses.append(item_add)
    elif choix_utilisateur == "2":
        item_delete = input ("What item do you wish to remove ? ")
        if item_delete in liste_de_courses:
            liste_de_courses.remove(item_delete)
print ("Bye")

【问题讨论】:

  • json.load() 方法(“load”中没有“s”)用于从文件中读取 JSON 编码数据并将其转换为 Python 字典。您正在尝试追加,就好像它是一个列表一样。
  • @JoeFerndz:不一定是 Python dict;合法的 JSON 包括简单的双引号字符串,或(方)括号数组。

标签: python list append attributeerror


【解决方案1】:

在此之后添加print(type(liste_de_courses))

with open (dossier, "r") as f:
    liste_de_courses = json.load(f)

liste_de_courses的类型是什么?

【讨论】:

  • 这是一个类型 > 我找到了问题,是我的JSON文件,谢谢你的帮助:)
【解决方案2】:

您的 JSON 文件存储的是 JSON 字符串 (Python str),而不是 JSON 数组 (Python list)。您需要修复输入文件。

【讨论】:

  • 谢谢 :) 我很好理解@ShadowRanger
【解决方案3】:

liste_de_courses 不是一个列表,而是一个字符串。 我对 json 一无所知,但请检查 json.load(f) 返回什么和哪种类型。

【讨论】:

  • 如果它帮助您将此答案标记为已接受,请。
猜你喜欢
  • 2013-11-08
  • 2021-12-26
  • 2020-08-08
  • 2021-01-10
  • 2020-05-05
  • 1970-01-01
  • 2012-08-30
  • 2014-05-09
相关资源
最近更新 更多