将 Python 3 open(encoding="utf-8") 向后移植到 Python 2 [英] Backporting Python 3 open(encoding="utf-8") to Python 2

查看:33
本文介绍了将 Python 3 open(encoding="utf-8") 向后移植到 Python 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个为 Python 3 构建的 Python 代码库,它使用带有编码参数的 Python 3 样式 open():

I have a Python codebase, built for Python 3, which uses Python 3 style open() with encoding parameter:

https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47

    with open(fname, "rt", encoding="utf-8") as f:

现在我想将此代码向后移植到 Python 2.x,以便我拥有一个适用于 Python 2 和 Python 3 的代码库.

Now I'd like to backport this code to Python 2.x, so that I would have a codebase which works with Python 2 and Python 3.

解决open() 差异和缺少编码参数的推荐策略是什么?

What's the recommended strategy to work around open() differences and lack of encoding parameter?

我能不能有一个 Python 3 open() 样式的文件处理程序来传输字节串,这样它就可以像 Python 2 open() 一样工作?

Could I have a Python 3 open() style file handler which streams bytestrings, so it would act like Python 2 open()?

推荐答案

1.在 Python 2 中获取编码参数:

如果你只需要支持 Python 2.6 和 2.7 你可以使用 io.open 而不是 open.io 是 Python 3 的新 io 子系统,它也存在于 Python 2,6 和 2.7 中.请注意,在 Python 2.6(以及 3.0)中,它纯粹是在 Python 中实现的,而且速度非常慢,因此如果您需要读取文件的速度,这不是一个好的选择.

1. To get an encoding parameter in Python 2:

If you only need to support Python 2.6 and 2.7 you can use io.open instead of open. io is the new io subsystem for Python 3, and it exists in Python 2,6 ans 2.7 as well. Please be aware that in Python 2.6 (as well as 3.0) it's implemented purely in python and very slow, so if you need speed in reading files, it's not a good option.

如果您需要速度,并且需要支持 Python 2.6 或更早版本,则可以使用 codecs.open 代替.它还有一个编码参数,与 io.open 非常相似,只是它处理行尾的方式不同.

If you need speed, and you need to support Python 2.6 or earlier, you can use codecs.open instead. It also has an encoding parameter, and is quite similar to io.open except it handles line-endings differently.

open(filename, 'rb')

注意b",意思是二进制".

Note the 'b', meaning 'binary'.

这篇关于将 Python 3 open(encoding="utf-8") 向后移植到 Python 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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