在 python 中整齐地打印 .txt 文件

Neatly printing a .txt file in python

我有一个 .txt 文件,其中包含如下文本:

Project Gutenberg Australia
a treasure-trove of literature
treasure found hidden with no evidence of ownership

但每当我尝试在 Python 中读取此文件时(使用 Flask - 我正在将文件上传到站点),使用以下行:

    if request.method == 'POST':
        f = request.files['file']
        f.save(secure_filename(f.filename))
        f.stream.seek(0)
        content = f.read()
    return render_template("book.html", text=content)

我的 "book.html" 文件如下所示:

<pre>
{{ text }}
</pre>

我得到如下内容:

b'\xef\xbb\xbf\r\nProject Gutenberg Australia\r\na treasure-trove of literature\r\ntreasure found hidden with no evidence of ownership\r\n\r\n\r\n\r\n\r\...]

如何解决这个问题,使我网站上显示的内容与 .txt 文件中显示的内容一样?我是否需要修改 "book.html" 或仅使用 Python 以不同方式读取文件?

谢谢!

您只需要 .decode() 您的字节数:

print(b'\xef\xbb\xbf\r\nProject Gutenberg Australia\r\na treasure-trove of literature\r\ntreasure found hidden with no evidence of ownership\r\n\r\n\r\n\r\n\r\...]'.decode())

给出:


Project Gutenberg Australia
a treasure-trove of literature
treasure found hidden with no evidence of ownership



\...]