io.StringIO 类 只能用于文本, io.BytesIO 类 操作二进制数据
当你想模拟一个普通的文件的时候 StringIO 和 BytesIO 类是很有用的。比如,在单元测试中,你可以使用 StringIO 来创建一个包含测试数据的类文件对象,这个对象可以被传给某个参数为普通文件对象的函数。
需要注意的是, StringIO 和 BytesIO 实例并没有正确的整数类型的文件描述符。因此,它们不能在那些需要使用真实的系统级文件如文件,管道或者是套接字的程序中使用。
下面是例子说明:
# -*- coding: utf-8 -*-
import io
import PyPDF2
import json
import zipfile
import requests
s1 = io.StringIO()
s1.write('Hello World\n')
print('This is a test', file=s1)
# Get all of the data written so far
print(s1.getvalue())
# Wrap a file interface around an existing string
s2 = io.StringIO('Hello\nWorld\n')
print(s2.read(4))
print(s2.read())
s3 = io.BytesIO()
s3.write(b'binary data')
s3.getvalue()
# 简单使用,内存中操作zip合并, pdf合并等
def compress_file_create_zip(**kwargs):
"""
压缩文件为zip(内存中操作)
"""
try:
file = io.BytesIO()
with zipfile.ZipFile(file, 'w') as myzip:
for name, value in kwargs.items():
myzip.writestr(name, value)
zip_data = file.getvalue()
return zip_data
except Exception as e:
raise Exception('压缩文件为zip,发生异常')
def memory_merge_many_pdf(file_byte):
"""
在内存中操作pdf合并为一个pdf,返回合成的二进制流
"""
try:
merge_pdf = PyPDF2.PdfFileMerger()
for one_byte in file_byte:
merge_pdf.append(PyPDF2.PdfFileReader(one_byte))
file = io.BytesIO()
merge_pdf.write(file)
return file.getvalue()
except Exception as e:
raise Exception('在内存中操作pdf合并为一个pdf,发生异常')
def pdf_data_save_disk(route, pdf_data):
"""
将合并的pdf保存到磁盘 测试使用,非必要无需将pdf写到本地
"""
try:
with open(route+'.pdf', 'wb') as pdffile:
pdffile.write(pdf_data)
except Exception as e:
raise Exception('将压缩的文件保存到磁盘发生异常')