Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

python - how to replace item in list if the title already exists in the text file?

So basically I'm trying to make it so that if the user puts in a title in the form that matches a title in the list, it replaces that title and it's content. But I don't know how to do that.

@route('/update', method="POST")
def update_article():
    """
    Receives page title and contents from a form, and creates/updates a
    text file for that page.
    """

    title = getattr(request.forms, "title")
    content = getattr(request.forms, "content")


    articles = read_articles_from_file()
    articles.append({
        "title": title,
        "content": content
    })

    my_file = open("storage/articles.json", "w")
    my_file.write(json.dumps(articles, indent=3))
    my_file.close()

    return redirect('/wiki/<pagename>')

question from:https://stackoverflow.com/questions/65540631/how-to-replace-item-in-list-if-the-title-already-exists-in-the-text-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can do something like this: (not too elegant way tho)

...
articles = read_articles_from_file()

append_flag = True
for i, article in enumerate(articles):      # loop through existing articles
    if title == article['title']:           # if new title is already exists 
        articles[i]['content'] = content    # update content of that article
        append_flag = False                 # update flag to false
        break                               # break the loop, assumed title is unique 

if append_flag:                             # append new record 
    articles.append({
        "title": title.strip(),             # strip out spaces, to ensure str==str comparison for content updates 
        "content": content
    })
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...