简体   繁体   English

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

[英]Neatly printing a .txt file in python

I have a .txt file with text like the following: 我有一个.txt文件,其文本如下所示:

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

but whenever I try to read this file in Python (using Flask - I'm uploading the file to a site), using the following lines: 但是每当我尝试使用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)

My "book.html" file is like the following: 我的“ book.html”文件如下所示:

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

I get something like the following: 我得到类似以下内容:

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\...]

How can I fix this so that what is displayed on my site is just like what is displayed in the .txt file? 如何解决此问题,以便网站上显示的内容与.txt文件中显示的内容相同? Do I need to modify "book.html" or just read the file differently with Python? 我需要修改“ book.html”还是只用Python读取文件?

Thanks! 谢谢!

You just need to .decode() your bytes: 您只需要.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())

gives: 得到:


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



\...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM