繁体   English   中英

如果标题已存在于文本文件中,如何替换列表中的项目?

[英]how to replace item in list if the title already exists in the text file?

所以基本上我试图做到这一点,以便如果用户以与列表中的标题匹配的形式输入标题,它会替换该标题及其内容。 但我不知道该怎么做。

@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>')

你可以这样做:(不是太优雅的方式)

...
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
    })
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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