转化的过程用到了 shutil 的copyfileobj 和 BytesIO, 如下:from shutil import copyfileobjtemp_file = BytesIO()copyfileobj 代码如下:from shutil import copyfileobjtemp_file = BytesIO()copyfileobj(img_obj.stream, temp_file)client.upload_fileobj break fdst.write(buf)"""从上述代码的最后一行看,fdst.write(buf) ,此时写“文件”的游标已经到“文件”的最后"""我们再来看下面有关 BytesIO In [2]: f = BytesIO() 所以,解决办法就是利用 seek(0) 把游标位置再次放到 0 处正确代码如下:from shutil import copyfileobjtemp_file = BytesIO()copyfileobj
StringIO和BytesIO很多时候,数据读写不一定是文件,也可以在内存中读写。StringIO就是在内存中读写str。 StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。 BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes:>>> from io import BytesIO>>> f = BytesIO()>>> f.write 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取:>>> from io import BytesIO>>> f = BytesIO(b'\xe4\xb8\xad \xe6\x96\x87')>>> f.read()b'\xe4\xb8\xad\xe6\x96\x87'StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口
1.1通过StringIO写入内存 例子 #from io import StringIO from io import BytesIO as StringIO output = StringIO() 1: s = output.readline() if s == "": break print s.strip() 结果: hello world hello China 2.BytesIO 模块 StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO;BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes 例子 from io import StringIO,BytesIO f = BytesIO() f.write(b"hello") f.write(b"\n") f.write("world") print(f.getvalue ()) g = BytesIO("hello\nworld") print(g.getvalue()) 结果: hello world hello world
Python中提供了StringIO和BytesIO这两个类将字符串数据和二进制数据写入到内存里。 StringIO StringIO可以将字符串写入到内存中,像操作文件一样操作字符串。 f.readline()) # print(f.readlines()) # 需要调用getvalue()方法才能获取到写入到内存中的数据 print(f.getvalue()) f.close() BytesIO 如果想要以二进制的形式写入数据,可以使用BytesIO类,它的用法和StringIO相似,只不过在调用write方法写入时,需要传入二进制数据。 from io import BytesIO f = BytesIO() f.write('你好\r\n'.encode('utf-8')) f.write('中国'.encode('utf-8'))
在django中使用 views.py from django.http import HttpResponse import qrcode from django.utils.six import BytesIO makeqrcode(request,data): url = HOST+data img = qrcode.make(url) #传入网址计算出二维码图片字节数据 buf = BytesIO () #创建一个BytesIO临时保存生成图片数据 img.save(buf) #将图片字节数据放到BytesIO临时保存 image_stream = buf.getvalue() #在BytesIO临时保存拿出数据 response
例如,逗号分隔文件(CSV)使用逗号(,)或分号(;)作为分隔符: >>> data = "1, 2, 3\n4, 5, 6" >>> np.genfromtxt(BytesIO(data), delimiter (data),) array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]) >>> np.genfromtxt(BytesIO(data), . 例如,如果我们只想导入第一列和最后一列,可以使用usecols =(0, -1): >>> data = "1 2 3\n4 5 6" >>> np.genfromtxt(BytesIO(data), 第一种可能性是使用显式结构化dtype,如前所述: >>> data = BytesIO("1 2 3\n 4 5 6") >>> np.genfromtxt(data, dtype=[(_, int) 如果我们为关键字赋予任何其他值,新名称将覆盖我们可能已使用dtype定义的字段名称: >>> data = BytesIO("1 2 3\n 4 5 6") >>> ndtype=[('a',int),
如果要操作二进制数据,就需要使用BytesIO。 1、要把str写入StringIO或者二进制数据写入BytesIO,我们需要先创建一个StringIO或者BytesIO,然后像文件一样写入即可: from io import StringIO f=StringIO from io import BytesIO f=BytesIO() f.write('中文'.encode('utf-8')) #请注意,写入的不是str,而是经过UTF-8编码的bytes。 初始化BytesIO,然后像读文件一样读取: from io import StringIO f=StringIO('Hello! from io import BytesIO f=BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') f.read() print(f.getvalue()) 结果:b’\xe4\
实现rc4库 非常简洁,看代码吧 import base64 import hashlib import os from io import BytesIO class RC4(object): s[i], s[j] = s[j], s[i] yield s[(s[i] + s[j]) % 256] def encrypt(in_stream: BytesIO , out_stream: BytesIO, pwd: str): rc4_cryptor = RC4(pwd) rc4_cryptor.encode(in_stream, out_stream ) def encrypt_str(data: str, pwd: str): in_stream = BytesIO() out_stream = BytesIO() data_bytes def decrypt_str(data: str, pwd: str): data_bytes = base64.urlsafe_b64decode(data) in_stream = BytesIO
不想要在生成后再提供给用户下载 解决: 使用BytesIO在内存中写入数据,而不是落地到本地中。 # 栗子 from io import BytesIO import zipfile from django.http import FileResponse def view(): download_io = BytesIO() with zipfile.ZipFile(pb_zip_io, "w", zipfile.ZIP_DEFLATED) as zip_fp: zip_fp.open
2.StringIO和BytesIO StringIO: StringIO顾名思义就是在内存中读写str。 BytesIO: StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。 BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes: >>> from io import BytesIO >>> f = BytesIO() >>> f.write 和StringIO类似,可以用一个bytes初始化BytesIO,然后,像读文件一样读取: >>> from io import BytesIO >>> f = BytesIO(b'\xe4\xb8\xad
---- StringIO && BytesIO StringIO 很多时候,数据读写不一定是文件(存放硬盘中),也可以在内存中读写。 StringIO顾名思义就是在内存中读写str。 hello~~\nhello zhdya") while True: aa = f.readline() if aa == '': break print(aa) BytesIO StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。 BytesIO实现了在内存中读写bytes,我们创建一个BytesIO,然后写入一些bytes: from io import BytesIO f = BytesIO() f.write("i wanna 小结 StringIO和BytesIO是在内存中操作str和bytes的方法,使得和读写文件具有一致的接口。
import urllib3 import os #PIL图像处理标准库 from PIL import Image from io import BytesIO http = urllib3.PoolManager 8d5494eef01f3a29f863534d9725bc315d607c8e.jpg') result = response.data #将bytes结果转化为字节流 bytes_stream = BytesIO Image.open(bytes_stream) # roiimg.show() #展示图片 #print(type(result)) #print(response.status) imgByteArr = BytesIO
请使用io.BytesIO作为替代。 > # Save to file>>> x = torch.tensor([0, 1, 2, 3, 4])>>> torch.save(x, 'tensor.pt')>>> # Save to io.BytesIO buffer>>> buffer = io.BytesIO()>>> torch.save(x, buffer)
self.curl.setopt(pycurl.WRITEFUNCTION, buff.write) 注意一下python3中StringIO()的包路径为io.StringIO 将以上StringIO()改为: buff = BytesIO () self.curl.setopt(pycurl.WRITEFUNCTION, buff.write) 同样的BytesIO()的包路径为io.BytesIO
image,cv2.COLOR_BGR2RGB)) return image 2、PIL和base64转换 ##PIL转base64 import base64 from io import BytesIO def pil_base64(image): img_buffer = BytesIO() image.save(img_buffer, format='JPEG') byte_data base64_str = base64.b64encode(byte_data) return base64_str base64转PIL import base64 from io import BytesIO PIL import Image def base64_pil(base64_str): image = base64.b64decode(base64_str) image = BytesIO
我们需要自己动手找方法: 第一步是从文件读取XML: from zipfile import ZipFile from urllib.request import urlopen from io import BytesIO wordFile=urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read() wordFile=BytesIO(wordFile 改进后的程序代码如下: from zipfile import ZipFile from urllib.request import urlopen from io import BytesIO from BeautifulSoup wordFile=urlopen("http://pythonscraping.com/pages/AWordDocument.docx").read() wordFile=BytesIO
zipfile直接写入指定文件中:with zipfile.ZipFile(temp_path ,mode='w')as f: f.write(file)返回ByteIObuffer = io.BytesIO ---- except Exception as e: print("異常タイプ:%s"%type(e)) print("異常内容:%s"%e)2,不保存文件,返回【BytesIO urllib.parseimport zipfiledef write_file_to_zip(files:List[object]): """zip output \n return BytesIO without download args: files: [filename:str, file:BytesIO/BufferedReader] """ try: buffer = io.BytesIO() # param1:写入对象 buffer # param2:mode write # param3:compression
data=f.read() return HttpResponse(data) 方法三:保存在内存中(需要借助io模块) from PIL import Image from io import BytesIO (request) img=Image.new('RGB',(350,40),(123,222,222)) #颜色模式,长宽,rgb里面的颜色 #生成一个Byteio对象 f=BytesIO 把文件从对象中取出来 return HttpResponse(f.getvalue()) 方法四,保存内存又保存文件中 from PIL import Image from io import BytesIO img.save(f,'png') return HttpResponse(f.getvalue()) 四.画点画线 from PIL import Image from io import BytesIO print(new_text) #存在session中 request.session['code']=new_text #存内存 f = BytesIO
最近在写爬虫但是图片保存用了很多种方法都没办法实现 最后用这种方法实现了 import os,base64 import requests as req from PIL import Image from io import BytesIO bdfile.bluemoon.com.cn/group2/M00/0A/BA/wKg_HlwzY1SAIdXDAAFyo-ZOLKQ399.jpg") # 内存中打开图片 image = Image.open(BytesIO (response.content)) # 图片的base64编码 ls_f = base64.b64encode(BytesIO(response.content).read()) # base64
if isinstance(fp, io.BytesIO): with open(filename, 'rb') as f: fp.write(f.read()) bytesio = io.BytesIO() with open(temp_file, 'rb') as f: bytesio.write(f.read()) os.remove (temp_file) return Image.frombytes(bytesio) def convert(source, t_suffix): """ :param _incs(im) if t_suffix in ['MSP', 'XBM', 'PALM']: im = im.convert('1') bi = io.BytesIO