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

时间:2019-07-18 21:34:50

标签: python file flask text pretty-print

我有一个.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读取文件?

谢谢!

1 个答案:

答案 0 :(得分:1)

您只需要.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



\...]