While writing html textarea content in a file, python flask is adding additional new lines in the file.
There is no issue while reading the content on textarea.
Initial file content:
line1
Line2
Line 3
Line 4
Added one new line from UI:
line1
Line2
Line 3
line 3.1
Line 4
Content on test.txt after saving from UI:
line1
Line2
Line 3
line 3.1
Line 4
Can some one help to identify, why there is new lines getting added on saving from UI?
Below is the Fask code
@app.route('/edit_file', methods=['GET', 'POST'])
def edit_file():
if request.method == 'POST':
# Get the file contents from the form
file_contents = request.form['file_contents']
# Open the file for writing
with open('C:\Temp\test.txt', 'w') as f:
f.write(file_contents.rstrip())
f.close()
# Redirect the user to the home page
return redirect(url_for('home'))
else:
# Read the file contents
with open('C:\Temp\test.txt', 'r') as f:
file_contents = f.read()
# Render the edit file form
return render_template('resolve_conflict.html', file_contents=file_contents, file_name=123)
# This route will render the home page
@app.route('/', methods=['GET', 'POST'])
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
2
Answers
Thanks for reply. It worked when we moved code to Linux. This issue in only on Windows.
The newline characters
"n"
from your Python file will be converted to the system’s default newline ones when passed via the HTML form, which seems to be"rn"
in your case as you seem to be in Windows.This is the good old
CR-LF
Windows vs.LF
Unix topic.You could solve this issue in your program by one of the two ways:
P.S., your context manager will close the file for you, thats why you use it. You do not need to call file.close() manually within it again.