Python Flask 在保存时向文件添加额外的新行

问题描述 投票:0回答:1

在文件中写入 html 文本区域内容时,Python Flask 会在文件中添加额外的新行。 阅读textarea上的内容没有问题。

初始文件内容:

line1
Line2
Line 3
Line 4

从 UI 添加了一行新行:

line1
Line2
Line 3 
line 3.1
Line 4

从 UI 保存后 test.txt 上的内容:

第 1 行

2号线

3号线

第 3.1 行

4号线

有人可以帮助确定为什么从 UI 保存时会添加新行吗?

下面是Fask代码

@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)
python html python-3.x flask cgi
1个回答
0
投票

通过 HTML 表单传递时,Python 文件中的换行符

"\n"
将转换为系统默认的换行符,在您的情况下,这似乎是
"\r\n"
,就像您在 Windows 中一样。 这是古老的
CR-LF
Windows 与
LF
Unix 话题。

您可以通过以下两种方法之一在程序中解决此问题:

  1. 写入文件之前手动转换换行符
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. 告诉python,写入文件时使用哪个值作为换行符
 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.,您的上下文管理器将为您关闭该文件,这就是您使用它的原因。您不需要再次在其中手动调用 file.close() 。

© www.soinside.com 2019 - 2024. All rights reserved.