对于上下文,我尝试使用soap API的流式响应,该API应输出CSV文件。响应输出以base 64编码的字符串,我必须将其写入CSV文件。
api文档说必须逐个缓冲区地读取响应,但我不熟悉c#所以我不确定如何复制字节并在正确的上下文中写入。
这是我试图复制的代码。代码由api的文档提供:
byte[] buffer = new byte[4000];
bool endOfStream = false;
int bytesRead = 0;
using (FileStream localFileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
{
using (Stream remoteStream = client.DownloadFile(jobId, chkFormatAsXml.Unchecked))
{
while (!endOfStream)
{
bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
if (bytesRead > 0)
{
localFileStream.Write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
else
{
endOfStream = true;
}
}
}
}
我当前的python代码如下所示:
buffer = ???
bytesread = 0
with open('csvfile.csv','w') as file:
#opens Pickle file
with (open("data2.pkl", 'r+b')) as openfile:
print openfile
bytesread = len(openfile.read(4000))
if bytesread > 0:
?????
任何帮助都会非常感激,即使它只是指向正确的方向。我也有一些问题引用了同样的问题。
Write Streamed Response(file-like object) to CSV file Byte by Byte in Python
How to replicate C# .read(buffer, 0, buffer.Length) in Python
更新:
我的代码现在看起来像:
import shutil
with (open("data2.pkl", 'r')) as pklfile:
with open('csvfile4.csv', 'wb') as csvfile:
file.write(shutil.copyfileobj(pklfile,csvfile, 4000)
不幸的是,这只是将base64代码字面写入csv文件,我不确定如何正确解码