skip to Main Content

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


  1. Chosen as BEST ANSWER

    Thanks for reply. It worked when we moved code to Linux. This issue in only on Windows.


  2. 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:

    1. Manually convert the line-breaks before writing the file
    if request.method == 'POST':
            # Get the file contents from the form
            file_contents = request.form['file_contents']
            converted = "n".join([line.strip() for line in file_contents.splitlines()])
            # Open the file for writing
            with open('test.txt', 'w') as f:
                f.write(converted)
    
    1. Tell python, which value to use as newline character when writing the 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('test.txt', 'w', newline="n") as f:
                f.write(file_contents)
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search