How do I read in a text file in python 3.3.3 and store it in a variable?

假装没事ソ 提交于 2020-01-06 13:25:30

问题


How do I read in a text file in python 3.3.3 and store it in a variable? I'm struggling with this unicode coming from python 2.x


回答1:


Given this file:

utf-8:   áèíöû

This works as you expect (IFF utf-8 is your default encoding):

with open('/tmp/unicode.txt') as f:
    variable=f.read()

print(variable)  

It is better to explicitly state your intensions if you are unsure what the default is by using a keyword argument to open:

with open('/tmp/unicode.txt', encoding='utf-8') as f:
    variable=f.read()

The keyword encodings supported are in the codec module. (For Python 2, you need to use codecs open to open the file rather than Python 2's open BTW.)



来源:https://stackoverflow.com/questions/21540006/how-do-i-read-in-a-text-file-in-python-3-3-3-and-store-it-in-a-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!