<p>首先,<a href="https://docs.python.org/2/library/json.html#json.dumps" rel="nofollow noreferrer">^{<cd1>}</a>“转储”到字符串,而不是文件。所以</p>
<pre><code>save_article = json.dumps(article, json_File)
</code></pre>
<p>将返回一个字符串,该字符串随后被绑定到<code>save_article</code>变量,但文件实际上没有被修改。您可能打算使用<a href="https://docs.python.org/2/library/json.html#json.dump" rel="nofollow noreferrer">^{<cd3>}</a>来接受文件作为第二个参数。</p>
<p>注意:在Python 2中,file参数被忽略,我假设您正在使用它,因为它在Python 3中会显示为一个错误。</p>
<hr/>
<p>可能还有其他问题。一种是文章将<em>附加到文件中,但代码的目的似乎是更新现有的文章。更新文本文件通常是不切实际的。一个更好的方法是遍历文章,更新与标题匹配的内容。然后在最后重写整个文件一次。下面是一个例子:</p>
<pre><code> with open("articles.json", 'r') as json_File:
articles = json.load(json_File)
# update any matching articles
for article in articles['article']:
if title == article['title']:
article['author'] = request.form['author']
article['text'] = request.form['text']
article['article_id'] = request.form['article_id']
# rewrite the whole JSON file with updated dictionary
with open("articles.json", 'w') as json_File:
json.dump(articles, json_File)
</code></pre>
<p>在更新项目数据时,您可能需要考虑使用一个简单的数据库来管理它。你可以看看<a href="http://flask-sqlalchemy.pocoo.org/2.3/" rel="nofollow noreferrer">Flask SQLAlchemy</a>。</p>