我想在烧瓶中的文本文件中进行搜索和替换。
@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和"输入()已经激活"误差修改。
这是一种正确的方法吗?我必须使用python 2.6
答案 0 :(得分:1)
您的代码将始终删除所有行,因为在两种情况下都不会将行写回文件,即当存在search_line时以及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'),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')