问题
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