简体   繁体   中英

Append in a list [Python]

could someone please explain to me why I have this error message :

line 27, in liste_de_courses.append(item_add)

AttributeError: 'str' object has no attribute 'append

Thank you in advance for your help

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")

Add print(type(liste_de_courses)) after this.

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

What is the type of liste_de_courses ?

Your JSON file is storing a JSON string (Python str ), not a JSON array (Python list ). You need to fix your input file.

The liste_de_courses is not a list but it is a string. I don't know anything about json but check that json.load(f) returns what and of which type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM