Python 在Flask中的文本文件中搜索并替换
我想在flask中的文本文件中搜索和替换Python 在Flask中的文本文件中搜索并替换,python,flask,Python,Flask,我想在flask中的文本文件中搜索和替换 @app.route('/links', methods=['POST']) def get_links(): search_line= "blah blah" try: for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt')): x = line.replace(search_line,
@app.route('/links', methods=['POST'])
def get_links():
search_line= "blah blah"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt')):
x = line.replace(search_line,
search_line + "\n" + request.form.get(u'query'))
except BaseException as e:
print e
return render_template('index.html')
这段代码总是删除我的txt文件中的所有行。我有unicode和“input()已激活”错误
这样做正确吗?我必须使用python 2.6您的代码将始终删除所有行,因为在两种情况下,即搜索行存在和搜索行不存在时,您都没有将行写回文件 请检查以下代码,并插入注释。
@app.route('/links', methods=['POST'])
def get_links():
search_line= "blah blah"
try:
for line in fileinput.input(os.path.join(APP_STATIC, u'links.txt'),inplace=1):
#Search line
if search_line in line:
#If yes Modify it
x = line.replace(search_line,search_line + "\n" + request.form.get(u'query'))
#Write to file
print (x)
else:
#Write as it is
print (x)
except BaseException as e:
print e
return render_template('index.html')
非常感谢。当我添加“\n”时,我有额外的空行。我怎样才能避免这种情况呢?在打印之前把它剥掉-打印(x.Strip())你让我开心。非常感谢。