[英]bug or feature: open and io.open are not interchangeable
I always thought open
and io.open
were interchangeable. 我一直认为open
和io.open
是可以互换的。
Apparently not, if I believe this snippet: 显然不是,如果我相信这个片段:
import ctypes, io
class POINT(ctypes.Structure):
_fields_ = [("x", ctypes.c_int),("y", ctypes.c_int)]
# THIS WORKS
with open("mypoints.bin", "wb") as f:
for i in range(10):
p = POINT(i,10-i)
print p.x, p.y
f.write(p)
# THIS FAILS
with io.open("mypoints.bin", "wb") as f:
for i in range(10):
p = POINT(i,10-i)
print p.x, p.y
f.write(p)
0 10
Traceback (most recent call last):
File "D:\test.py", line 10, in <module>
f.write(p)
File "c:\Python26\lib\io.py", line 1070, in write
self._write_buf.extend(b)
TypeError: 'POINT' object is not iterable
Note: I tested in Python 2.6.6 注意:我在Python 2.6.6中测试过
Yes, it's a "bug", io.open
in Python 2.6 is slightly broken. 是的,这是一个“bug”,Python 2.6中的io.open
稍微破了。 It was supposed to be work like 3.x's open
to ease transition, but it doesn't work correctly in some cases. 它应该像3.x那样open
以轻松过渡,但在某些情况下它无法正常工作。 For example, it doesn't support objects with the buffer interface like in your case. 例如,它不支持具有缓冲区接口的对象,就像您的情况一样。 This is fixed in Python 2.7 where the builtin open
can be used like the open
in 3.x, and io.open
is just an alias to it. 这在Python 2.7中得到修复,其中内置open
可以像3.x中的open
一样使用,而io.open
只是它的别名。
If you need binary mode, use open
, it behaves the same in 2.x and 3.x, with the only difference being that in 2.x it accepts for writing objects that it shouldn't (such as unicode
objects). 如果你需要二进制模式,使用open
,它在2.x和3.x中的行为相同,唯一的区别是2.x它接受写入它不应该的对象(例如unicode
对象)。 If you need text mode, use codecs.open
or io.open
with encoding
argument. 如果需要文本模式,请使用带encoding
参数的codecs.open
或io.open
。 Both are available in 3.x. 两者都有3.x.
But note that open
and io.open
were meant to not be interchangeable, because io
is Python 3's io
module, and in Python 3 open
is very different from the open
in Python 2.6 or less. 但请注意, open
和io.open
是不可互换的,因为io
是Python 3的io
模块,而Python 3中的open
与Python 2.6或更低版本中的open
是非常不同的。
http://docs.python.org/library/io.html http://docs.python.org/library/io.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.