简体   繁体   English

bug或功能:open和io.open不可互换

[英]bug or feature: open and io.open are not interchangeable

I always thought open and io.open were interchangeable. 我一直认为openio.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.openio.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. 但请注意, openio.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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM