0

Yesterday I asked a similar question about the filestream method, What is the Python equivalent to FileStream in C#?, but I now realize I should have probably been asking about the .read function instead.

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 do not know what to do with. Also the api documentation says that the response must be read to a destination buffer-by-buffer.

Here is the context in the code. 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;
         }
      }
   }
}

Any help would be greatly appreciated, even if it is just to point me in the right direction, as I am very lost now. I also, had another question referencing the same problem today as well. Write Streamed Response(file-like object) to CSV file Byte by Byte in Python

Community
  • 1
  • 1
walker_4
  • 433
  • 1
  • 7
  • 21
  • Just do `remoteStream.read(n)`, where `n` is how much you want to read. – DYZ Jan 26 '17 at 00:05
  • Thanks, Would you know how I could read a single buffer at a time? – walker_4 Jan 26 '17 at 00:10
  • What is a "buffer"? Do you know its size? If you do, just read that many bytes. – DYZ Jan 26 '17 at 00:12
  • Good q, looking at the code it looks like the buffer is created by: `byte[] buffer = new byte[4000]` – walker_4 Jan 26 '17 at 00:27
  • 1
    Since you know the size in C# `buffer.Length`, there must be a way to find it in Python, too. So, `read(4000)`. – DYZ Jan 26 '17 at 00:28
  • So should `len(openfile.read(4000))` be the equivalent of `bytesRead = remoteStream.Read(buffer, 0, buffer.Length)` as far as you know? Or am I misunderstanding? – walker_4 Jan 26 '17 at 00:46
  • 1
    Affirmative. It will be. – DYZ Jan 26 '17 at 00:55
  • Thanks a lot! Would you know the python equivalent of `localFileStream.Write(buffer, 0, bytesRead)`or at least be able to briefly describe what the `bytes[4000]` variable means in the context of the Write function? Your help has been greatly appreciated! – walker_4 Jan 26 '17 at 01:13

1 Answers1

0

It looks like bytesread = len(openfile.read(4000)) is the correct way to replicate bytesRead = remoteStream.Read(buffer, 0, buffer.Length);

Thanks DYZ

walker_4
  • 433
  • 1
  • 7
  • 21