How to replicate C# 'byte' and 'Write&

2019-08-17 07:56发布

For context I am trying to consume a streamed response from a soap API, which should output a CSV file. The response outputs a string coded in base 64, which I must write into the CSV file.

The api documentation says that the response must be read to a destination buffer-by-buffer, but I am unfamiliar with c# so I am unsure on how to replicate byte and write in the correct context to do so.

Here is the the code I am trying to replicate. The code was provided by the api's documentation:

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;
         }
      }
   }
}

My current python code looks like this:

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:
            ?????

Any help would be greatly appreciated, even if it is just to point me in the right direction. I have also had a few questions referencing this same problem.

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

UPDATE:

My code now looks like:

import  shutil

with (open("data2.pkl", 'r')) as pklfile:
    with open('csvfile4.csv', 'wb') as csvfile:
        file.write(shutil.copyfileobj(pklfile,csvfile, 4000)

Unforunately, this just writes the base64 code literally to the csv file, and i'm not sure how to decode properly

0条回答
登录 后发表回答