[英]Read/Open image from instance of Python io.BufferedReader class
[英]Using io.BufferedReader on a stream obtained with open()?
我想使用缓冲流,因为我想使用peek()
方法向前查看,但使用我的流与另一个需要类文件对象的方法。 (我使用seek()
但可能必须处理不支持随机访问的管道输入I / O.)
但是这个测试用例失败了:
AttributeError:'file'对象没有属性'_checkReadable'
import sys
import io
srcfile = sys.argv[1]
with open(srcfile, 'rb') as f:
fbuf = io.BufferedReader(f)
print fbuf.read(20)
发生了什么,我该如何解决? 我以为BufferedReader旨在缓冲流。 如果是这样,为什么open()
函数不会返回与它兼容的东西?
通过print
语句的外观,您使用的是Python 2.在该版本中, file
不是BufferedReader
构造函数的有效参数:
在Python 2.x中,这被建议作为内置
file
对象的替代,但在Python 3.x中,它是访问文件和流的默认接口。 ( 1 )
您应该使用io.open
代替:
>>> f = io.open(".bashrc", "rb")
如果你这样做,就没有必要将它显式地包装在BufferedReader
因为这正是io.open
默认返回的内容:
>>> type(f)
<type '_io.BufferedReader'>
有关详细信息,请参阅其文档 ; 有一个控制缓冲的buffering
参数。
在Python 3中, open is io.open
因此两个I / O库已合并为一个。 似乎io
被添加到Python 2.6中主要是为了向前兼容。
您可以通过将buffering
参数传递给open来设置缓冲量(以字节为单位):
import sys
srcfile = sys.argv[1]
with open(srcfile, 'rb', buffering=30) as f:
print(f.peek(30))
print(f.read(20))
这是一个BufferedReader
:
>>> with open("test.txt", 'rb', buffering=30) as f:
... type(f)
<class '_io.BufferedReader'>
请注意,默认情况下,它被缓冲为1
行缓冲。
在Python2中,如果必须使用open
返回的file
对象(或者例如由某些无法修改的模块例程提供),则可以使用fileno()
获取的io.FileIO
作为io.FileIO
构造函数,然后传递io.FileIO
对象到io.BufferedReader
构造函数。
因此,您可以按如下方式重写示例代码:
import sys
import io
srcfile = sys.argv[1]
with open(srcfile, 'rb') as f:
fio = io.FileIO(f.fileno())
fbuf = io.BufferedReader(fio)
print fbuf.read(20)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.