file-io - 如何在 python 3.3.3 中读取文本文件并将其存储在变量中?

标签 file-io python-3.x python-unicode

如何在 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/

相关文章:

python-3.x - Python 3 中的自定义文件类型

Python io 模块的 TextIOWrapper 或 BuffereRWPair 函数不能很好地与 pySerial 配合使用

python - Perl 的 (<>) 在 Python 中的等价物是什么? fileinput 没有按预期工作

python - 在 tkinter,python 中以像素为单位设置标签宽度

java - 在 Java 中自动重新加载更改的文件

python - 将 static() 添加到 urlpatterns 只能通过附加到列表来工作

Python 打印带有\u 转义的 json,解码错误

Python 正则表达式在查找特殊 unicode 字符时遇到问题

java - 将文件读入字符串的最简单方法是什么?

java - 从带有分隔符的文件中读取