我想尝试python BytesIO类.
作为一个实验,我尝试写入内存中的zip文件,然后从该zip文件中读取字节.因此gzip,我传入一个BytesIO对象,而不是传入一个文件对象.这是整个脚本:
from io import BytesIO
import gzip
# write bytes to zip file in memory
myio = BytesIO()
g = gzip.GzipFile(fileobj=myio, mode='wb')
g.write(b"does it work")
g.close()
# read bytes from zip file in memory
g = gzip.GzipFile(fileobj=myio, mode='rb')
result = g.read()
g.close()
print(result)
Run Code Online (Sandbox Code Playgroud)
但它正在返回一个空bytes对象result.这在Python 2.7和3.4中都会发生.我错过了什么?
我用google搜索并在SO上搜索这些缓冲模块之间的区别.但是,我仍然不太了解,我认为我读到的一些帖子已经过时了.
在Python 2.7.11中,我使用了下载了特定格式的二进制文件r = requests.get(url).然后我通过StringIO.StringIO(r.content),cStringIO.StringIO(r.content)并io.BytesIO(r.content)设计用于解析内容的功能.
所有这三种方法都可用.我的意思是,即使文件是二进制文件,它仍然可以使用StringIO.为什么?
另一件事是他们的效率.
In [1]: import StringIO, cStringIO, io
In [2]: from numpy import random
In [3]: x = random.random(1000000)
In [4]: %timeit y = cStringIO.StringIO(x)
1000000 loops, best of 3: 736 ns per loop
In [5]: %timeit y = StringIO.StringIO(x)
1000 loops, best of 3: 283 µs per loop
In [6]: %timeit y = io.BytesIO(x)
1000 loops, best of 3: 1.26 ms per loop
Run Code Online (Sandbox Code Playgroud)
如上图所示 …
我正在使用PIL的Pillow fork并继续收到错误
OSError:无法在0x103a47468>处识别图像文件<_io.BytesIO对象
当试图打开图像时.我使用virtualenv与python 3.4并没有安装PIL.
我试图根据遇到同样问题的其他人找到解决方案,然而,这些解决方案对我不起作用.这是我的代码:
from PIL import Image
import io
# This portion is part of my test code
byteImg = Image.open("some/location/to/a/file/in/my/directories.png").tobytes()
# Non test code
dataBytesIO = io.BytesIO(byteImg)
Image.open(dataBytesIO) # <- Error here
Run Code Online (Sandbox Code Playgroud)
图像存在于文件的初始打开中,并转换为字节.这似乎适用于几乎所有人,但我无法弄清楚为什么它失败了.
编辑:
dataBytesIO.seek(0)
Run Code Online (Sandbox Code Playgroud)
因为我不是通过流保存图像,所以我不是通过流保存图像,因此我只是用数据实例化BytesIO,因此(如果我正确地想到这一点),搜索应该已经为0.
嗨,我正在尝试将我的 df 转换为二进制并将其存储在一个变量中。
我的_df:
df = pd.DataFrame({'A':[1,2,3],'B':[4,5,6]})
Run Code Online (Sandbox Code Playgroud)
我的代码:
import io
towrite = io.BytesIO()
df.to_excel(towrite) # write to BytesIO buffer
towrite.seek(0) # reset pointer
Run Code Online (Sandbox Code Playgroud)
我正进入(状态 AttributeError: '_io.BytesIO' object has no attribute 'write_cells'
完整追溯:
AttributeError Traceback (most recent call last)
<ipython-input-25-be6ee9d9ede6> in <module>()
1 towrite = io.BytesIO()
----> 2 df.to_excel(towrite) # write to BytesIO buffer
3 towrite.seek(0) # reset pointer
4 encoded = base64.b64encode(towrite.read()) #
C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\frame.py in to_excel(self, excel_writer, sheet_name, na_rep, float_format, columns, header, index, index_label, startrow, startcol, engine, merge_cells, encoding, inf_rep, …Run Code Online (Sandbox Code Playgroud) 因此,将BytesIO对象写入文件的快速方法是使用:
with open('myfile.ext', 'wb') as f:
f.write(myBytesIOObj.getvalue())
myBytesIOObj.close()
Run Code Online (Sandbox Code Playgroud)
但是,如果我想迭代myBytesIOObj而不是将其写入一个块,我将如何进行呢?我在使用Python 2.7.1.另外,如果BytesIO很大,那么迭代编写是否会更有效?
谢谢
我正在尝试编写python 2/3兼容代码来将字符串写入csv文件对象.这段代码:
line_as_list = [line.encode() for line in line_as_list]
writer_file = io.BytesIO()
writer = csv.writer(writer_file, dialect=dialect, delimiter=self.delimiter)
for line in line_as_list:
assert isinstance(line,bytes)
writer.writerow(line)
Run Code Online (Sandbox Code Playgroud)
在Python3上给出了这个错误:
> writer.writerow(line)
E TypeError: a bytes-like object is required, not 'str'
Run Code Online (Sandbox Code Playgroud)
但是assert对类型没有问题,为什么要csv创建错误呢?
我不能BytesIO只用于Python 2和3吗?这里的问题在哪里?
我有一个文件,想将其转换为BytesIO对象,以便将其存储在数据库的 varbinary 列中。
请任何人都可以帮助我使用python转换它。
下面是我的代码:
f = open(filepath, "rb")
print(f.read())
myBytesIO = io.BytesIO(f)
myBytesIO.seek(0)
print(type(myBytesIO))
Run Code Online (Sandbox Code Playgroud) 根据BytesIO 文档:
获取缓冲区()
返回对缓冲区内容的可读和可写视图,而不复制它们。此外,改变视图将透明地更新缓冲区的内容:
获取值()
返回包含缓冲区全部内容的字节。
所以看起来好像getbuffer更复杂。但是如果你不需要一个可写的视图呢?然后你会简单地使用getvalue? 有哪些取舍?
在这个例子中,它们似乎做的完全一样:
# Create an example
from io import BytesIO
bytesio_object = BytesIO(b"Hello World!")
# Write the stuff
with open("output.txt", "wb") as f:
f.write(bytesio_object.getbuffer())
Run Code Online (Sandbox Code Playgroud) 我想管一io.BytesIO() bytetream到一个单独的程序使用subprocess.popen() ,但我不知道如何,或者如果这是在所有可能的.文档和示例都是关于文本和换行的.
当我掀起这样的事情时:
import io
from subprocess import *
stream = io.BytesIO()
someStreamCreatingProcess(stream)
command = ['somecommand', 'some', 'arguments']
process = Popen(command, stdin=PIPE)
process.communicate(input=stream)
Run Code Online (Sandbox Code Playgroud)
我明白了
Traceback (most recent call last):
File "./test.py", line 9, in <module>
procOut = process.communicate(input=stream)
File "/usr/lib/python2.7/subprocess.py", line 754, in communicate
return self._communicate(input)
File "/usr/lib/python2.7/subprocess.py", line 1322, in _communicate
stdout, stderr = self._communicate_with_poll(input)
File "/usr/lib/python2.7/subprocess.py", line 1384, in _communicate_with_poll
chunk = input[input_offset : input_offset + _PIPE_BUF]
TypeError: '_io.BytesIO' object has no attribute …Run Code Online (Sandbox Code Playgroud) 我正在尝试理解io.BytesIO的write()和read()方法.我的理解是我可以使用io.BytesIO,因为我会使用File对象.
import io
in_memory = io.BytesIO(b'hello')
print( in_memory.read() )
Run Code Online (Sandbox Code Playgroud)
上面的代码将按预期返回b'hello',但下面的代码将返回一个空字符串b''.
import io
in_memory = io.BytesIO(b'hello')
in_memory.write(b' world')
print( in_memory.read() )
Run Code Online (Sandbox Code Playgroud)
我的问题是:
- io.BytesIO.write(b' world')到底做了什么?
- io.BytesIO.read()和io.BytesIO.getvalue()有什么区别?
我假设答案与io.BytesIO是一个流对象有关,但我不清楚大局.