Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Python 2.x 文件对象readinto与Python 3.x的博弈 #1

Open
limboinf opened this issue Jan 13, 2016 · 1 comment
Open

Python 2.x 文件对象readinto与Python 3.x的博弈 #1

limboinf opened this issue Jan 13, 2016 · 1 comment

Comments

@limboinf
Copy link
Owner

Python 2.x readinto说不要用它,在《Python 核心编程》中也提到:

file.readinto(buf, size): 从文件读取size个字节到buf缓冲区(已不支持)

但是在《Python Cookbook》中却多次使用它,如5.9 读取二进制数据到可变缓冲区中, 让我还纳闷啊。

但是使用过程中确实感觉到这个家伙的强大。

我需要赶紧在电脑上装python 3.x 看下这个家伙与python2.x的区别在哪里,是否废弃了,还是改进了。

@limboinf
Copy link
Owner Author

memoryview()内置函数,用于返回对象obj的内存查看对象。所谓内存查看对象,就是对象符合缓冲区协议的对象,为了给别的代码使用缓冲区里的数据,而不必拷贝,就可以直接使用。

>>> buf = bytearray(12)
>>> buf
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
>>> m1 = memoryview(buf)
>>> m1
<memory at 0x105907b00>
>>> m2 = m1[-5:]
>>> m2
<memory at 0x105907b98>
>>> m2[:] = b'WORLD'
>>> buf
bytearray(b'\x00\x00\x00\x00\x00\x00\x00WORLD')
>>> print buf
WORLD

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant