如何在 python 3.3.3 中读取文本文件并将其存储在变量中?我正在努力处理来自 python 2.x 的 unicode
最佳答案
给定此文件:
utf-8: áèíöû
这正如您所期望的那样工作(IFF utf-8 是您的默认编码):
with open('/tmp/unicode.txt') as f:
variable=f.read()
print(variable)
如果您不确定默认值是什么,最好通过使用 open 的关键字参数来明确说明您的意图。 :
with open('/tmp/unicode.txt', encoding='utf-8') as f:
variable=f.read()
关键字encodings supported位于编解码器模块中。 (对于 Python 2,您需要使用编解码器 open 来打开文件,而不是 Python 2 的 open 顺便说一句。)
关于file-io - 如何在 python 3.3.3 中读取文本文件并将其存储在变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21540006/