如何在python 3.3.3中读取文本文件并将其存储在变量中? [英] How do I read in a text file in python 3.3.3 and store it in a variable?

查看:56
本文介绍了如何在python 3.3.3中读取文本文件并将其存储在变量中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在python 3.3.3中读取文本文件并将其存储在变量中?我正在为来自python 2.x的unicode苦苦挣扎

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

推荐答案

给出此文件:

utf-8:   áèíöû

这按预期工作( IFF utf-8是您的默认编码):

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()

关键字受支持的编码位于编解码器模块中.(对于Python 2,您需要使用编解码器打开来打开文件而不是Python 2的打开 BTW.)

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.)

这篇关于如何在python 3.3.3中读取文本文件并将其存储在变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆